You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的BeautifulSoup提取网页食谱板块的特定href

提取指定网站食谱板块的特定链接

核心思路

要精准筛选目标链接,需通过两步过滤:

  1. 先锁定域名属于https://fitaliancook.com的链接
  2. 再匹配食谱板块的特征路径(比如该网站食谱链接通常以/recipe/开头,需根据实际页面结构调整)

代码实现示例

from bs4 import BeautifulSoup
import requests

# 1. 获取目标页面内容
target_page_url = "你要爬取的页面URL"  # 比如网站首页或食谱列表页
response = requests.get(target_page_url)
soup = BeautifulSoup(response.text, "html.parser")

# 2. 筛选符合条件的食谱链接
recipe_links = []
# 遍历所有带href属性的a标签
for a_tag in soup.find_all("a", href=True):
    href = a_tag["href"]
    # 处理完整域名的食谱链接
    if href.startswith("https://fitaliancook.com/recipe/"):
        recipe_links.append(href)
    # 处理相对路径的食谱链接
    elif href.startswith("/recipe/"):
        full_link = "https://fitaliancook.com" + href
        recipe_links.append(full_link)

# 可选:去重避免重复链接
unique_recipe_links = list(set(recipe_links))

# 输出结果
for link in unique_recipe_links:
    print(link)

关键调整说明

  • 路径匹配修改:如果该网站食谱板块的路径不是/recipe/,需查看页面实际链接结构,把判断条件改成对应特征(比如包含/recipes/或特定关键词)
  • 相对路径兼容:部分页面链接是不带域名的相对路径,必须拼接完整域名才能得到有效访问链接
  • 去重必要性:页面内可能存在重复的食谱入口链接,用集合去重后转成列表即可解决

内容的提问来源于stack exchange,提问作者Rakshit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:15:38