web-scraping in python using beautiful soup: AttributeError: 'NoneType' object has no attribute 'text'

web-scraping in python using beautiful soup: AttributeError: 'NoneType' object has no attribute 'text'

我正在使用 html 请求和漂亮的汤开发网络爬虫(我是新手)。对于 1 个网页 (https://www.superdrug.com/Make-Up/Face/Primer/Face-Primer/Max-Factor-False-Lash-Effect-Max-Primer/p/788724),我正在尝试获取产品的价格。 HTML 是:

<span class="pricing__now" itemprop="price">8.99</span>

我试过使用 soup.find 和 soup.find_all:

r = session.get(link)
r.html.render(sleep=3, timeout=30)
soup = BeautifulSoup(r.content, 'lxml')
price = soup.find('span', itemprop="price").text
r = session.get(link)
r.html.render(sleep=3, timeout=30)
soup = BeautifulSoup(r.content, 'lxml')
price = soup.find_all('span', itemprop="price").text

和r.html.find:

r = session.get(link)
r.html.render(sleep=6, timeout=30)
price = r.html.find('body > div.pdp-container > div.content-wrapper.pdp > div > div > div.pdp__purchase-options > div.pricing > span:nth-child(2)', first=True).text

None 并返回空列表,或者 AttributeError: 'NoneType' object has no attribute 'text'。我不确定为什么我无法获取此信息。任何帮助将不胜感激。

您可以从页面中嵌入的 Json 数据中获取价格。例如:

import json
import requests
from bs4 import BeautifulSoup

url = "https://www.superdrug.com/Make-Up/Face/Primer/Face-Primer/Max-Factor-False-Lash-Effect-Max-Primer/p/788724"
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0"
}

soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")

data = json.loads(soup.select('[type="application/ld+json"]')[1].contents[0])

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

print(data["offers"]["price"])

打印:

8.99