如何解决当相关变量具有值时,为什么我的 BeautifulSoup 代码会收到属性错误?
我将 Python 3.9.1 与 selenium 和 BeatifulSoup 结合使用,以便为 Tesco 的网站(一个自学的小项目)创建我的第一个网络爬虫。但是,当我运行代码时,如下所示,我收到一个属性错误:
Traceback (most recent call last):
File "c:\Users\Ozzie\DropBox\My PC (DESKTOP-HFVRPAV)\Desktop\Tesco\Tesco.py",line 37,in <module>
clean_product_data = process_products(html)
File "c:\Users\Ozzie\DropBox\My PC (DESKTOP-HFVRPAV)\Desktop\Tesco\Tesco.py",line 23,in process_products
weight = product_price_weight.find("span",{"class":"weight"}).text.strip()
AttributeError: 'nonetype' object has no attribute 'find'
我不确定出了什么问题 - 标题和 URL 部分工作正常,但重量和价格部分返回此值。当我尝试打印 product_price 和 product_price_weight 变量时,它们返回了我期望的值(我不会在这里发布,它只是很长的 HTML)。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
import time
from bs4 import BeautifulSoup
driver = webdriver.Chrome(ChromeDriverManager().install())
def process_products(html):
clean_product_list = []
soup = BeautifulSoup(html,'html.parser')
products = soup.find_all("div",{"class":"product-tile-wrapper"})
for product in products:
data_dict = {}
product_details = product.find("div",{"class":"product-details--content"})
product_price = product.find("div",{"class":"price-control-wrapper"})
product_price_weight = product.find("div",{"class":"price-per-quantity-weight"})
data_dict['title'] = product_details.find('a').text.strip()
data_dict['product_url'] = ('tesco.com') + (product_details.find('a')['href'])
weight = product_price_weight.find("span",{"class":"weight"}).text.strip()
data_dict['price'] = product_price.find("span",{"class":"value"}).text.strip()
data_dict['price'+weight] = product_price_weight.find("span",{"class":"value"}).text.strip()
clean_product_list.append(data_dict)
return clean_product_list
master_list = []
for i in range (1,3):
print (i)
driver.get(f"https://www.tesco.com/groceries/en-GB/shop/fresh-food/all?page={i}&count=48")
html = driver.page_source
driver.maximize_window()
clean_product_data = process_products(html)
master_list.extend(clean_product_data)
print (master_list)
非常感谢任何帮助。 非常感谢,
解决方法
您可以通过更新 process_products
函数来尝试此操作。再次注意存在以下情况,其中您尝试执行的某些变量 .find()
返回 None
,这仅表示它没有 > find
任何基于 .find()
函数给出的参数的元素。
例如:
假设这部分代码已经执行了
product_details = product.find("div",{"class":"product-details--content"})
现在,如果它根据这些 tags
& class
找到一个元素,它将返回一个 bs4
对象,但如果没有,它将返回 None
所以假设它返回了 { {1}}。
因此,您的 None
变量将是一个 product_details
对象,因此一旦它在您的代码中再次变为 None
,您就可以执行此操作。再次,None
是 product_details
None
所以我在这里所做的是将它放在 data_dict['title'] = product_details.find('a').text.strip()
#Another way of saying is
#data_dict['title'] = None.find('a').text.strip() ##Clearly an ERROR
try
中以简单地捕获这些错误并为您提供空字符串,表明您的变量可能正在尝试执行 {{1} } 返回一个 except
或者可能是一些错误(关键是没有返回相关数据),这就是为什么我使用 .find()
None
但你也可以只做一个 {{1 }} try
,但我认为在 except
if
中这样做更好。
else
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。