python - 如何使用 BeautifulSoup 从 HTML div 标签文件中提取文本?
问题描述
我的python代码如下:
import requests
from bs4 import BeautifulSoup
flipurl = "https://www.flipkart.com/search?q=realme+7&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=off&as=off"
r = requests.get(flipurl)
htmlContent = r.content
soup = BeautifulSoup(htmlContent,'html.parser')
#i scrape flipkart product price
price= soup.find_all("div",class_="_30jeq3 _1_WHN1")
print(price.get_text())
#**I got this error how I get text:**
"ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all()
when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
正如您从上面的代码片段中看到的那样,我试图提取所有文本,但我得到了一个错误并且没有。请解决这个问题
解决方案
根据 BeautifulSoup文档,find_all
返回元素列表。因此,您正在调用price.get_text()
一个列表,这会导致错误,因为该方法仅由单个元素实例拥有。
AttributeError:ResultSet 对象没有属性“get_text”。您可能将元素列表视为单个元素。当您打算调用 find() 时,您是否调用了 find_all()?
错误消息提示您希望在单个元素而不是集合上调用此方法。
如果我们打印出您的price
变量,我们会得到以下信息:
<div class="_30jeq3 _1_WHN1">₹15,499</div>
<div class="_30jeq3 _1_WHN1">₹13,499</div>
<div class="_30jeq3 _1_WHN1">₹15,499</div>
...
假设您想要每个 div 中的文本列表,只需对结果执行列表理解:
price_elements = soup.find_all("div",class_="_30jeq3 _1_WHN1")
prices_text = [p.get_text() for p in price_elements]
这将为您提供以下列表
['₹15,499', '₹13,499', '₹15,499', '₹13,499', '₹19,999', '₹29,999', '₹29,999', '₹7,499', '₹7,499', '₹9,999', '₹8,999', '₹7,999', '₹7,999', '₹9,999', '₹8,999', '₹16,999', '₹16,999', '₹14,999', '₹14,999', '₹11,999', '₹8,999', '₹8,999', '₹12,999', '₹11,999']
推荐阅读
- javascript - 带对话框的 Javascript 构造函数
- php - 使用php降序
- scala - 查找不同行中两个时间戳之间的持续时间
- nginx - 带有别名的 nginx try_files 不起作用,但 rewrite 可以
- react-native - 是否可以导入我的照片以响应本机应用程序并将它们分享到 instagram
- python - 如何通过切片在字典python中分别获取键和值
- python - 我们将如何使用输入语句的输出,将使用什么来代替命令中的 (is) 和命令中的生日运行
- python - 如何在python中解析具有相同类名的网站的多个属性?
- reactjs - 如何在 Mui 数据表中进行自定义重置行为
- java - Spring boot 控制器调用不支持内容类型“application/json;charset=UTF-8”