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

Python网页爬取(Beautiful Soup)代码异常,请求错误排查指导

代码错误排查及修正

核心问题点

  • CSS选择器错误:soup.select('div.row cf')写法不符合CSS选择器规则,cf是类名,正确的多类选择器需用.连接,且该选择器指向的是包含所有产品的父容器,你实际需要遍历的是父容器内的单个产品容器,正确的单个产品选择器应为div.item-container。
  • 无判断直接取列表元素易崩溃:使用select()[0]提取元素时,若找不到对应节点会直接抛出索引错误,建议改用select_one()获取单个元素,同时增加存在性判断避免程序崩溃。

修正后的代码

import requests
from bs4 import BeautifulSoup
import csv

page = requests.get("https://www.bathroomspareparts.co.uk/merlyn-two-panel-hinged-bath-screen-mb7-spare-parts-17909-c.asp")
soup = BeautifulSoup(page.content, 'html.parser')

all_products = []

# 选择单个产品的容器节点
products = soup.select('div.item-container')
for product in products:
    # 使用select_one安全获取元素
    name_elem = product.select_one('div.item-short-description')
    price_elem = product.select_one('div.item-price')
    
    # 元素存在时再提取内容
    if name_elem and price_elem:
        name = name_elem.text.strip()
        price = price_elem.text.strip()
        all_products.append({
            "Name": name,
            "Price": price,
        })

# 补充保存到CSV的逻辑(原代码未完成此部分)
with open('products.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=["Name", "Price"])
    writer.writeheader()
    writer.writerows(all_products)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:25:32