You need to enable JavaScript to run this app. 使用BeautifulSoup抓取H4属性及href获取产品对应价格问题求助
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup抓取H4属性及href获取产品对应价格问题求助

代码问题梳理
  • 循环变量定义错误:外层循环和内层循环都用了path作为变量名,且URL中用到的page变量未提前定义,内层循环本应该遍历页码,却错误复用了路径变量。
  • URL语法错误:URL字符串拼写大小写不匹配,定义时用小写url,发起请求时误用大写URL;路由拼接规则错误,缺少&page=参数标识,直接拼接页码会导致请求路径不合法。
  • 元素定位矛盾:前期查找h4标签的caption类,后续提取名称时又查找h2标签的caption类,定位规则不统一无法匹配到目标元素。
  • 数据存储逻辑错误:每次循环直接覆盖DataFrame的列,而非追加新行,会导致旧数据被新请求的数据覆盖;提取价格时用到的scrap_price变量未定义,语法不合法。
  • 匹配错位风险:单独提取所有名称和所有价格后直接赋值,若某产品缺少价格/名称会导致两类数据错位不匹配,也未实现需求里的href提取逻辑。
修正后可运行代码
import urllib3
from bs4 import BeautifulSoup
import pandas as pd

# 禁用urllib3的不安全请求警告,可根据需要删除
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
req = urllib3.PoolManager()
# 用列表暂存数据,避免每次循环操作DataFrame损耗性能
scrap_list = []

for path in range(10): # 遍历分类
    for page in range(10): # 遍历页面,修正循环变量名为page
        # 修正URL拼接规则
        url = f'https://www.samehgroup.com/index.php?route=product/category&page={page}&path={path}'
        res = req.request('GET', url)
        soup = BeautifulSoup(res.data, 'html.parser')
        # 先定位每个产品的父容器,避免名称、价格、链接错位
        product_items = soup.find_all('div', class_='product-thumb')
        for item in product_items:
            # 按需求用h4标签定位名称
            name_tag = item.find('h4', class_='caption')
            price_tag = item.find('div', class_='price')
            if name_tag and price_tag:
                # 提取h4内的产品链接
                a_tag = name_tag.find('a')
                product_href = a_tag['href'].strip() if a_tag and a_tag.has_attr('href') else ''
                scrap_list.append({
                    'product_name': name_tag.text.strip(),
                    'product_href': product_href,
                    'product_price': price_tag.text.strip()
                })

# 统一转为DataFrame,可通过df.to_csv('products.csv',index=False)保存到本地
df = pd.DataFrame(scrap_list)
print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 21:42:00