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

如何从Beautiful Soup 4的find_all返回结果中提取文本

错误原因

find_all() 函数返回的是符合匹配规则的标签对象列表,而get_text()是单个BeautifulSoup标签对象的专属方法,无法直接作用于列表对象,这是代码报错的核心原因。
另外你提供的复现代码缺少requests库的导入语句,运行前需要先安装依赖:

pip install requests lxml
修复方案

方案1:遍历所有匹配结果提取文本

如果需要获取所有符合条件的span标签的文本,遍历find_all()返回的列表逐个调用get_text()即可:

import requests
from bs4 import BeautifulSoup
page = requests.get("https://weather.com/en-IE/weather/tenday/l/e98742cdb581b2f4461e4f438badbfb0e16dc9e70ffbf4c8df1b0f7a4394f9f9")
soup = BeautifulSoup(page.content,"lxml")
info_list = soup.find_all("span", class_ = "DetailsSummary--extendedData--365A_")

for info in info_list:
    print(info.get_text())

方案2:仅提取第一个匹配结果的文本

如果你只需要第一个符合条件的标签内容,可以直接用find()方法替代find_all(),find()会直接返回单个标签对象,可直接调用get_text():

import requests
from bs4 import BeautifulSoup
page = requests.get("https://weather.com/en-IE/weather/tenday/l/e98742cdb581b2f4461e4f438badbfb0e16dc9e70ffbf4c8df1b0f7a4394f9f9")
soup = BeautifulSoup(page.content,"lxml")
info = soup.find("span", class_ = "DetailsSummary--extendedData--365A_")

print(info.get_text())

如果需要把所有提取到的文本合并为一个字符串,可以用列表推导式实现:

all_text = '\n'.join([item.get_text() for item in info_list])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:06:10