微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用漂亮的汤在 python 中进行网页抓取:AttributeError: 'NoneType' 对象没有属性 'text'

如何解决使用漂亮的汤在 python 中进行网页抓取:AttributeError: 'NoneType' 对象没有属性 '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,'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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。