当相关变量具有值时,为什么我的 BeautifulSoup 代码会收到属性错误?

如何解决当相关变量具有值时,为什么我的 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,您就可以执行此操作。再次,Noneproduct_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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?