首页 > 解决方案 > 甚至python代码似乎正确但出现属性错误,没有文字被刮掉

问题描述

当我使用 BeautifulSoup 来抓取列出的产品名称和价格时,类似的代码在其他网站上也有效。但是在这个网站上运行的时候,soup.findAll属性都存在,但是没有刮到文字,出现AttributeError。有没有人可以帮忙看一下代码和网站检查?

我检查并运行了很多次,同样的问题仍然存在

代码在这里:

url = 'https://shopee.co.id/Handphone-Aksesoris-cat.40'
re = requests.get(url,headers=headers)
print(str(re.status_code))
soup = BeautifulSoup(re.text, "html.parser")
for el in soup.findAll('div', attrs={"class": "collection-card_collecton-title"}):
    name = el.get.text()
    print(name)

AttributeError:“NoneType”对象没有属性“文本”

标签: objectweb-scrapingattributesattributeerrorfindall

解决方案


i在类名中缺少一个。但是,内容是从 API 调用动态加载的(这就是为什么在 js 不运行的调用中找不到它,因此下一次更新 DOM 的调用不会发生);您可以在网络选项卡中找到。它返回 json。

import requests

r = requests.get('https://shopee.co.id/api/v2/custom_collection/get?category_id=40&platform=0').json()
titles = [i['collection_title'] for i in r['collections'][0]['list_popular_collection']]
print(titles)

在此处输入图像描述


价格也:

import requests

r = requests.get('https://shopee.co.id/api/v2/custom_collection/get?category_id=40&platform=0').json()
titles,prices =zip(*[(i['collection_title'], i['price']) for i in r['collections'][0]['list_popular_collection']])
print(titles,prices)

推荐阅读