You need to enable JavaScript to run this app. 如何使用BeautifulSoup抓取goodricketea站点的商品href链接
优惠活动
大模型
产品
解决方案
定价
更多

如何使用BeautifulSoup抓取goodricketea站点的商品href链接

基于BeautifulSoup提取商品URL的实现方案

前置依赖安装

先安装需要用到的第三方库,执行以下命令即可:
pip install requests beautifulsoup4

完整实现代码

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import time

# 基础配置
base_domain = "https://www.goodricketea.com"
target_page = "https://www.goodricketea.com/product/darjeeling-tea"
# 模拟浏览器请求头,避免被站点反爬拦截
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

# 发送页面请求
time.sleep(1) # 添加请求间隔,避免触发反爬规则
response = requests.get(target_page, headers=headers)
response.encoding = response.apparent_encoding # 自动适配页面编码,避免乱码

product_urls = set() # 用集合存储链接可自动去重
if response.status_code == 200:
    soup = BeautifulSoup(response.text, "html.parser")
    # 定位所有商品卡片节点,可根据实际页面结构调整类名参数
    product_cards = soup.find_all("div", class_="product-item")
    for card in product_cards:
        a_tag = card.find("a", href=True)
        # 过滤出商品详情页的专属链接
        if a_tag and a_tag["href"].startswith("/product/"):
            # 把相对路径拼接为完整可访问的URL
            full_url = urljoin(base_domain, a_tag["href"])
            product_urls.add(full_url)

# 输出提取到的所有商品链接
for url in product_urls:
    print(url)

注意事项

  • 如果运行后没有提取到链接,可以打开目标页面按F12查看商品卡片对应的实际类名,替换find_all方法中的class_参数即可
  • 不要短时间内频繁发起请求,避免被站点限制访问
  • 爬取前请确认站点的robots.txt规则,遵守合规爬取要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 01:15:06