python爬取下厨房每周最受欢迎菜谱

python爬取下厨房每周最受欢迎菜谱

1、分析过程

1、进入网页——下厨房,右键->检查->Network->All,刷新网页点击第0个请求,再点击response。按下ctrl+f查找任意一个菜名,如能在response中找到,则数据放在html里。则可返回观察网页源代码,点击Elements。

注:如果在response中找不到数据,则数据应在XHR里,那么就要使用另一种方式抓取数据,本文只介绍在html里抓取数据
QQ截图

2、在Elements里找到我们需要抓取的数据(菜名、用料、链接),可以在菜名这里点击右键检查快速找到,可以发现菜名和链接放在标签
[p class=’‘name’’]里,用料则放在标签 [p class=“ing ellipsis”] 里。根据菜名的路径、URL的路径、食材的路径,我们可以找到这三者的最小共同父级标签,是:[div class=“recipe recipe-215-horizontal pure-g image-link display-block”]。 菜名和食材我们可以通过提取标签里的文本(text)得到,链接我们可以提取标签里的herf与https://www.xiachufang.com/做拼接获得。本周最受欢迎菜谱里一共有20页,观察网址我们发现,只需要通过改变链接末尾的page=的数值即可实现翻页。
在这里插入图片描述

2、代码实现

1、模块导入

#没有模块的请先下载相关模块,可以在终端输入 **pip install 模块名** 下载,或者在pycharm软件中点击
File->Setting->project->python interpreter 里下载。
#使用request来获取数据,使用BeautifulSoup来解析数据,使用csv或者openpyxl来存储数据。
import requests,csv,openpyxl
from bs4 import BeautifulSoup

2、获取解析数据

#获取所有目标url,本周最受欢迎菜谱里一共有20页,观察网址我们发现,只需要通过改变链接末尾的page=的数值即可实现翻页。
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36'} #添加request headers,伪装成浏览器登录,若不添加则会被浏览器认出来是爬虫,而有的浏览器会限制爬虫,比如下厨房。
foods_list = [] #存储食物数据
for i in range(1,21):
    url = 'https://www.xiachufang.com/explore/?page='+str(i) #通过改变i的数值达到爬取所有网页的目的
    res = requests.get(url,headers=headers) #获取数据
    soup = BeautifulSoup(res.text,'html.parser') #解析数据
    inf = soup.find_all('div',class_="recipe recipe-215-horizontal pure-g image-link display-block") #找到最小父级共同标签
   	for food in inf:
       food_name = food.find('img')['alt'] #菜名
       food_ingredients = food.find('p',class_='ing ellipsis').text #食材
       food_href = 'https://www.xiachufang.com/'+ food.find('a')['href'] #链接
       foods_list.append([food_name,food_href,food_ingredients]) #把获取的数据添加到列表
       print('菜名:\t%s\n用料:\t%s链接:\t%s\n'%(food_name,food_ingredients,food_href)) #打印    

代码写到这里可进行编译(编译结果部分截图):
部分打印结果

3、数据存储

  • 存储为xlsx格式
#使用xlsx存储,需要导入openxlsx模块
wb = openpyxl.Workbook() #创建工作薄
sheet = wb.active #获取工作薄活动表
sheet.title = 'menu' #命名
headers = ['菜品','链接','用料'] #表头
sheet.append(headers)
for food in foods_list:
    sheet.append(food) #添加数据
wb.save('xiachufang.xlsx') #保存

部分数据截图-xlsx

  • 存储为csv格式
#使用csv保存,需要导入csv模块。
#调用open()函数打开csv文件,参数为: 文件名'下厨房.csv',写入模式 'w',newline='',encoding='utf-8'。
with open('下厨房.csv','w',newline='',encoding='utf-8')as file:
    header = ['菜品','链接','用料'] #表头
    writer = csv.writer(file) #创建writer对象
    writer.writerow(header) #添加表头
    for food in foods_list:
        writer.writerow(food) #添加数据

部分数据截图-csv

4、完整代码

import requests,pprint,csv,openpyxl
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36'} #添加request headers,伪装成浏览器登录,若不添加则会被浏览器认出来是爬虫,而有的浏览器会限制爬虫,比如下厨房。
foods_list = [] #存储食物数据

for i in range(1,21):
    url = 'https://www.xiachufang.com/explore/?page='+str(i) #通过改变i的数值达到爬取所有网页的目的
    res = requests.get(url,headers=headers) #获取数据
    soup = BeautifulSoup(res.text,'html.parser') #解析数据
    inf = soup.find_all('div',class_="recipe recipe-215-horizontal pure-g image-link display-block") #找到最小父级共同标签
    for food in inf:
        food_name = food.find('img')['alt']  # 菜名
        food_ingredients = food.find('p', class_='ing ellipsis').text  # 食材
        food_href = 'https://www.xiachufang.com/' + food.find('a')['href']  # 链接
        foods_list.append([food_name, food_href, food_ingredients])  # 把获取的数据添加到列表
        print('菜名:\t%s\n用料:%s链接:\t%s\n' % (food_name, food_ingredients, food_href))  # 打印

wb = openpyxl.Workbook() #创建工作薄
sheet = wb.active #获取工作薄活动表
sheet.title = 'menu' #命名
headers = ['菜品','链接','用料'] #表头
sheet.append(headers)
for food in foods_list:
    sheet.append(food) #添加数据
wb.save('xiachufang.xlsx') #保存

3、总结

代码及xlsx,提取码:3xx2

over,新手小白,多多指教。

使用 XPath 爬取下厨房菜谱数据也是一种常见的方法。步骤如下: 1. 使用 requests 库向下厨房菜谱搜索页面发送请求,获取 HTML 页面内容。 2. 使用 lxml 库解析 HTML 页面,创建 XPath 对象。 3. 使用 XPath 对象提取菜谱列表,以及每道菜谱的详细页面链接。 4. 遍历菜谱列表,使用提取到的详细页面链接,向每道菜谱的详细页面发送请求,获取 HTML 页面内容。 5. 使用 XPath 对象提取菜谱的详细信息,例如食材、做法等。 下面是一个简单的 Python 爬取下厨房菜谱的示例代码: ```python import requests from lxml import etree # 发送请求,获取搜索页面的 HTML 内容 url = 'https://www.xiachufang.com/search/?keyword=红烧肉' response = requests.get(url) html = response.text # 解析 HTML 页面,创建 XPath 对象 selector = etree.HTML(html) # 提取菜谱列表,以及每道菜谱的详细页面链接 recipe_list = selector.xpath('//div[@class="recipe"]') for recipe in recipe_list: recipe_link = recipe.xpath('./a/@href')[0] # 发送请求,获取详细页面的 HTML 内容 recipe_response = requests.get(recipe_link) recipe_html = recipe_response.text # 解析 HTML 页面,创建 XPath 对象 recipe_selector = etree.HTML(recipe_html) # 提取菜谱的详细信息 recipe_name = recipe_selector.xpath('//h1[@class="page-title"]/text()')[0] recipe_ingredients = recipe_selector.xpath('//div[@class="ings"]/text()')[0] recipe_steps = recipe_selector.xpath('//div[@class="steps"]/ol/li/p/text()') # 打印菜谱的详细信息 print(recipe_name) print(recipe_ingredients) print(recipe_steps) ``` 注意,XPath 的语法需要熟悉,可以通过 Chrome 浏览器的开发者工具,选中网页中的元素,然后右键选择 Copy -> Copy XPath,获取该元素的 XPath 表达式。同时,爬取网站内容时需要遵守网站的爬虫协议,不要过度频繁地发送请求,以免对网站造成影响。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值