首页 > 解决方案 > 如何使用 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()?

正如您从上面的代码片段中看到的那样,我试图提取所有文本,但我得到了一个错误并且没有。请解决这个问题

标签: pythondjangoweb

解决方案


根据 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']

推荐阅读