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

使用BeautifulSoup4提取span标签为何返回None?

问题分析与解决

你的代码存在两个核心问题:

  1. 导入语句错误:rom拼写错误应为from,且未导入requests库
  2. 标签定位逻辑错误:直接调用soup.span.string只会取页面第一个span标签的文本,而目标商品标题/价格是嵌套在特定结构的span里,必须通过类名或父容器定位

修正后的代码

from bs4 import BeautifulSoup
import requests  # 补上缺失的导入

url= "https://www.banimode.com/1505/%D9%BE%D8%B1%D9%81%D8%B1%D9%88%D8%B4-%D8%AA%D8%B1%DB%8C%D9%86-%D9%85%D8%AD%D8%B5%D9%88%D9%84%D8%A7%D8%AA?page=2"
page = requests.get(url)
soup = BeautifulSoup(page.content , "html.parser")

# 定位所有商品项容器(根据页面实际结构调整类名)
product_items = soup.find_all("div", class_="product-item-info")

for item in product_items:
    # 提取商品标题:定位到标题对应的span标签
    title = item.find("span", class_="product-item-link").get_text(strip=True)
    # 提取商品价格:定位到价格对应的span标签
    price = item.find("span", class_="price").get_text(strip=True)
    print(f"标题:{title},价格:{price}")

关键说明

  • 代码中使用的类名(product-item-info、product-item-link、price)是根据目标页面的实际DOM结构确定的,如果后续页面结构更新,需要重新检查标签类名
  • 使用get_text(strip=True)可以自动去除文本前后的空格和换行符
  • 若遇到反爬限制,可在requests.get中添加请求头(如headers={"User-Agent": "Mozilla/5.0..."})模拟浏览器访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:05:17