使用BeautifulSoup爬取食谱时无法正确提取h2标题与p内步骤生成目标字典
Simply Recipes 网站食谱爬取代码调整指南
现有代码的问题定位
- 容器选择错误:之前验证过可以正常返回烹饪步骤的DOM容器是
id="sr-recipe-method"的div,修改代码时错误替换为id="sr-recipe-callout"区块,该区块不包含烹饪步骤内容,自然拿不到有效数据。 - 变量作用域错误:之前写的列表推导式中引用的
p是无定义的变量,没有基于目标容器遍历内部的标签,导致筛选结果始终为空数组。
- 标题定位逻辑偏差:从错误的callout区块找h2标签取标题,和页面实际的标题DOM位置不匹配。
调整后的完整可运行代码
import requests from bs4 import BeautifulSoup # 静态请求目标食谱页面 target_url = "https://www.simplyrecipes.com/recipes/cooking_for_two_strawberry_almond_oat_smoothie/" response = requests.get(target_url) soup = BeautifulSoup(response.text, "html.parser") # 抓取食谱标题:页面顶层h1标签为食谱正式名称 recipe_title = soup.find("h1").get_text(strip=True) # 定位烹饪步骤专属容器(沿用之前验证过的选择器) method_container = soup.find("div", attrs={"id": "sr-recipe-method"}) # 收集烹饪步骤,仅保留包含加粗引导的段落 cooking_steps = [] for p_tag in method_container.find_all("p"): if p_tag.find("strong"): # 清理文本中的多余换行、连续空格 clean_step = " ".join(p_tag.text.split()) cooking_steps.append(clean_step) # 组装为目标格式的字典 final_result = {recipe_title: cooking_steps} print(final_result)
运行输出效果
执行代码后将得到完全符合要求的结构:
{'Strawberry Almond Oat Smoothie Recipe': [ '1 Combine the ingredients: In a blender, combine the oats, strawberries, yogurt, almond milk, banana, and almond extract.', '2 Puree the smoothie: Starting on low speed, puree the ingredients. Turn the blender on high and continue to puree until smooth. Serve right away.' ]}
冗余代码清理提示
- 原代码中引入的
ScraperAPIClient、Splinter、webdriver_manager相关逻辑在当前静态页面请求场景下没有实际作用,可以全部删除减少运行时依赖。 - 不要随意替换已经验证过能正确返回内容的DOM选择器,一旦选错容器节点,后续所有元素定位逻辑都会失效。
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

