【发布时间】:2021-05-25 13:55:29
【问题描述】:
我正在尝试使用 BeautifulSoup 和请求来搜索谷歌购物。这是我的代码,非常简单:
from bs4 import BeautifulSoup
import requests
import lxml
import json
def gshop(q):
q = q.replace(' ', '+')
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
response = requests.get(f'https://www.google.com/search?q={q}&tbm=shop', headers=headers).text
soup = BeautifulSoup(response, 'lxml')
data = []
for container in soup.findAll('div', class_='sh-dgr__content'):
title = container.find('h4', class_='A2sOrd').text
price = container.find('span', class_='a8Pemb').text
supplier = container.find('div', class_='aULzUe IuHnof').text
buy = 'https://google.com'+(container.find('a', class_='eaGTj mQaFGe shntl')['href'])
rating = container.find('span', class_='Rsc7Yb').text
data.append({
"Title": title,
"Price": price,
"Rating": rating,
"Supplier": supplier,
"Link": buy
})
return json.dumps(data, indent = 2, ensure_ascii = False)
print(gshop('toys'))
这会引发错误:
Traceback (most recent call last):
File "c:/Users/Maanav/Desktop/ValRal/main.py", line 45, in <module>
print(gshop('toys'))
File "c:/Users/Maanav/Desktop/ValRal/main.py", line 34, in gshop
rating = container.find('span', class_='Rsc7Yb').text
AttributeError: 'NoneType' object has no attribute 'text'
请查看谷歌购物网址的来源以更好地理解我的代码。出了什么问题?
【问题讨论】:
-
浏览量如此之多,但没有答案:(
-
如果您尝试打印
response.url,您将得到https://www.google.com/search?q=toys&tbm=shop,但不会产生任何结果。 -
我无法复制您的代码,因为进入该 URL 会要求您登录 google,而 soup 根本无法读取该页面。
-
@solopiu 它没有要求我登录
-
您的代码假设您将找到每个产品的所有值。例如,某些产品不会有评级。所以程序将通过异常。尝试对标题和评级进行例外处理。例如 -
try: title = container.find('h4', class_='A2sOrd').text except: title="None"还有另一种调试方法是在 HTML 上编写响应并查看返回的内容。with open("r3.html","w") as f: f.write(response)
标签: python html web-scraping beautifulsoup python-requests