使用 BeautifulSoup 时出现 AttributeError

AttributeError when using BeautifulSoup

我正在编写一个脚本来生成 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)

我在 return 中收到的错误消息是: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 class 的任何内容,但这没有任何意义。

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

查看站点源代码,id="pageBody" 的元素是 div,而不是 h1。因此,当您使用 source.find 时,它会 returns None。尝试:

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

您不需要 product_feed,删除它并将下一行更改为:

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

最后可以验证:print(len(all_products)) 48