【问题标题】:BeautifulSoup AttributeErrorBeautifulSoup 属性错误
【发布时间】: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&amp;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


【解决方案1】:

由 cmets 中的 @simpleApp 解决:

有时,谷歌购物清单上的产品可能没有评级,或者卖家可能没有添加供应商名称。这将停止程序运行。为了阻止这种情况发生,我们必须使用异常处理。

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'):
        try:
            title = container.find('h4', class_='A2sOrd').text
        except:
            title = None
        try:
            price = container.find('span', class_='a8Pemb').text
        except:
            price = None
        try:
            supplier = container.find('div', class_='aULzUe IuHnof').text
        except:
            supplier = None
        try:
            buy = 'https://google.com'+(container.find('a', class_='eaGTj mQaFGe shntl')['href'])
        except:
            buy = None
        try:
            rating = container.find('span', class_='Rsc7Yb').text
        except:
            rating = None
        data.append({
            "Title": title,
            "Price": price,
            "Rating": rating,
            "Supplier": supplier,
            "Link": buy
        })

    return json.dumps(data, indent = 2, ensure_ascii = False)

【讨论】:

  • 谢谢你,自我!这为我解决了问题!
猜你喜欢
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
相关资源
最近更新 更多