python - 使用 BeautifulSoup 时出现 AttributeError

标签 python python-3.x beautifulsoup attributeerror

我正在编写一个脚本来生成 JSON 文件,但遇到了一些问题。

import requests
from bs4 import BeautifulSoup

url = requests.get('https://www.perfectimprints.com/custom-promos/20492/Beach-Balls.html')
source = BeautifulSoup(url.text, 'html.parser')

product_feed = source.find('div', id_="pageBody")

products = product_feed.find_all('div', class_="product_wrapper")

single_product = products[0]

product_name = single_product.find('div', class_="product_name")
product_name = product_name.a.text

sku = single_product.find('div', class_="product_sku")
sku = sku.text

def get_product_details(product):
  product_name = product.find('div', class_="product_name").a.text
  sku = single_product.find('div', class_="product_sku").text
  return {
    "product_name": product_name,
    "sku": sku
  }

all_products = [get_product_details(product) for product in products]
print(all_products)

我收到的错误消息是:Traceback (most recent call last): File "scrape.py", line 9, in <module> products = product_feed.find_all('div', class_="product_wrapper") AttributeError: 'NoneType' object has no attribute 'find_all'

根据我的阅读,这是因为它没有找到任何关于 product_wrapper 的信息类,但这没有任何意义。

最佳答案

问题是 product_feed = source.find('h1', id_="pageBody") 正在返回 None。我尝试了您的代码,product_feed = source.find_all('h1') 仅返回 1 个没有 ID 信息的项目。

关于python - 使用 BeautifulSoup 时出现 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52898498/

相关文章:

python - 在 Python 中使用生成器/"with ... as"的紧凑方式

python - python中的链式调用父初始化器

python-3.x - 无法使用 pip 安装 sent2trash

python - 在 python 字典中使用单引号和双引号之间有什么区别(如果有的话)?

python - 如何用 BeautifulSoup [Python] 抓取表格

python - 如何访问这个没有 id 的 <div class> 内的文本?使用BeautifulSoup

python - 如何将 pandas DataFrame 中的行从 Series 转换回 DataFrame?

python - Jupyter 在 Mac 上安装失败

python - 从系列列表创建数据框

python - 使用 Python 进行更快的解析