【发布时间】:2021-04-05 09:42:18
【问题描述】:
我使用 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)
非常感谢任何帮助。 非常感谢,
【问题讨论】:
-
您在循环中执行“product.find()”,因此它可以返回“无”。在使用从结果中分配的任何变量之前,您应该检查这一点。
-
感谢您的建议。您究竟如何建议我这样做?
-
你好 Ozgur,是的!不知何故,你的这个变量
process_products weight它的值是None,你正在对它做一个.find()。所以是的,它确实会导致错误。 -
您通常如何检查“无”?
-
您应该在您的问题中至少包含一个产品标签 -
"div",{"class":"product-tile-wrapper"}- 格式化为代码。可能有更好的方法可以从中提取信息。
标签: python html selenium beautifulsoup attributeerror