本文仅供学习参考。
薄荷健康秉承“为年轻家庭提供更健康、更美味的食品和饮料”的公司使命,为8000万用户提供个性化智能营养处方与一站式健康解决方案,致力于成为年轻家庭首选的健康生活方式品牌。
左侧是食物的大类,右侧是具体的食物。
程序要做的事情,就是进入每个食物大类,然后爬取右侧各类食物,进行翻页爬取。
前端页面最大展示100条记录,所以程序也就爬取100条(10页)
逻辑:进入第一个大类->查询第一页->查询第二页->……->查询最后一页->
进入第二个大类->……
……
进入最后一个大类->……
使用的Python模块
import requests from lxml import etree
获取所有大类,把大类的URL和标题存到列表中
start_url = "http://www.boohee.com/food/group/1"
resp = requests.get(url=start_url, headers=headers)
html = etree.HTML(resp.text)
cate_list = html.xpath("//ul[@class='group-list']/li")
cate_url_list = list()
cate_name_list = list()
for cate in cate_list:
cate_url = cate.xpath(".//a/@href")[0]
cate_name = cate.xpath(".//a/text()")[0]
cate_url_list.append(cate_url)
cate_name_list.append(cate_name)
得到了大类的URL,进入每个大类,然后一页页翻页
for index, cate_url in enumerate(cate_url_list):
item_dict = dict()
item_dict['cate_name'] = cate_name_list[index]
item_dict['cate_url'] = cate_url
for page in range(1, 11):
url = "http://www.boohee.com{}?page={}".format(cate_url, format(page))
resp = requests.get(url=url, headers=headers)
html = etree.HTML(resp.text)
food_list = html.xpath("//ul[@class='food-list']/li")
for food in food_list:
food_name = food.xpath(".//div[contains(@class, 'text-box')]//a/@title")[0]
food_calory = food.xpath(".//div[contains(@class, 'text-box')]//p/text()")[0]
item_dict['food_name'] = food_name
item_dict['food_calory'] = food_calory
print(item_dict)
完整代码:
添加微信,回复:薄荷网;获取全部代码。