【问题标题】:I am trying to scrape a website for my project but I am stuck with an error. Take a look and let me know if anyone have suggestion for this我正在尝试为我的项目抓取一个网站,但我遇到了一个错误。看看,让我知道是否有人对此有建议
【发布时间】:2020-12-05 13:09:22
【问题描述】:
html_text = requests.get('https://www.trustpilot.com/categories/restaurants_bars? 
numberofreviews=0&status=claimed&timeperiod=0').text
soup = BeautifulSoup(html_text, 'lxml')
restaurants = soup.find_all('a', class_ = 'internal___1jK0Z wrapper___26yB4')
for index, restaurant in enumerate(restaurants):
    name = restaurant.find('div', class_ = 'businessTitle___152-c').text
    rating = restaurant.find('div', class_ = 'textRating___3F1NO').text
    with open('{index}.csv', 'a') as f:
        f.write(name)
        f.write(',')
        f.write(rating)
        f.write('\n')

    print('File saved')

这是引发错误的代码。

Traceback(最近一次调用最后一次): 文件“main.py”,第 8 行,在 name = restaurant.find('div', class_ = 'businessTitle___152-c').text AttributeError: 'NoneType' 对象没有属性 'text'

【问题讨论】:

    标签: python web-scraping beautifulsoup python-requests


    【解决方案1】:

    运行您的代码并打印出相关位。您所定位的类集 internal___1jK0Z wrapper___26yB4 不仅用于餐厅网站,还用于页面页脚中的 about 链接。我认为这组类用于每个链接,而不仅仅是餐厅网站的链接。

    【讨论】:

    • 是的,马修,我从您的回答中了解到如何抓取网站以排除此错误。
    【解决方案2】:

    您正在尝试访问 None 类型的对象的属性,可能您的查询之一是返回 None

    【讨论】:

    • 我想不通,谢谢,我现在正在深入研究我的代码。
    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 2020-12-12
    • 2020-10-11
    • 2021-05-18
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多