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

如何从BeautifulSoup返回的嵌套列表中提取text文本并解决ResultSet报错

问题原因
  • BeautifulSoup的find_all()方法返回的是ResultSet对象,本质是Tag元素的集合,本身不支持text属性,只有单个Tag元素才能调用text属性提取文本。
  • 你代码中的PrecioCromos是两层嵌套结构:外层是每个页面对应的ResultSet结果集,内层才是符合条件的span标签元素,直接遍历外层对象调用text必然报错。
修改方案

方案1:嵌套循环提取所有价格文本

适合需要收集所有页面所有价格的场景,代码如下:

from typing import List
from bs4 import BeautifulSoup
import requests
import pandas as pd
from decimal import Decimal

ListaPreciosCromos = list()

ListaUrl = ['https://steamcommunity.com/market/search?category_753_Game%5B%5D=tag_app_495570&category_753_cardborder%5B%5D=tag_cardborder_0&category_753_item_class%5B%5D=tag_item_class_2#p1_price_asc', 'https://steamcommunity.com/market/search?category_753_Game%5B%5D=tag_app_540190&category_753_cardborder%5B%5D=tag_cardborder_0&category_753_item_class%5B%5D=tag_item_class_2#p1_price_asc', 'https://steamcommunity.com/market/search?category_753_Game%5B%5D=tag_app_607210&category_753_cardborder%5B%5D=tag_cardborder_0&category_753_item_class%5B%5D=tag_item_class_2#p1_price_asc']
PageCromos = [requests.get(x) for x in ListaUrl]
SoupCromos = [BeautifulSoup(x.content, "html.parser") for x in PageCromos]
PrecioCromos = [x.find_all("span", {"data-price": True}) for x in SoupCromos]

PreciossinText = []
# 先遍历每个页面的结果集
for page_result in PrecioCromos:
    # 再遍历结果集中的每个span标签,提取文本存入列表
    for price_tag in page_result:
        PreciossinText.append(price_tag.text.strip())

print(PreciossinText)

方案2:扁平化列表推导式

语法更简洁,效果和方案1完全一致:

# 替换原有的循环代码即可
PreciossinText = [price_tag.text.strip() for page_result in PrecioCromos for price_tag in page_result]

特殊场景:每个页面只取第一个价格

如果你的需求是每个页面仅提取第一个符合条件的价格,可直接将find_all替换为find,修改对应行即可:

# 修改PrecioCromos的生成逻辑
PrecioCromos = [x.find("span", {"data-price": True}) for x in SoupCromos]
# 直接遍历提取文本
PreciossinText = [x.text.strip() for x in PrecioCromos if x]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:09:04