【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' BeautifulSoup ParsingAttributeError: 'NoneType' 对象没有属性 'text' BeautifulSoup 解析
【发布时间】:2020-12-12 13:29:22
【问题描述】:

我成功地从新闻站点获取所有标题,但在获取所有数据后,python 程序崩溃并出现以下错误:

Traceback (most recent call last):
File "c:\Users\HP\Desktop\My Python Projects\pratidintime.py", line 14, in <module>
print(title.text.strip())
AttributeError: 'NoneType' object has no attribute 'text'

这是我的代码:

import requests
from bs4 import BeautifulSoup


headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}

    r = requests.get('https://www.pratidintime.com/category/pratidin-exclusive/', headers = headers)
    soup = BeautifulSoup(r.text, 'lxml')
    item_inner = soup.find_all('div', {'class' : 'item-inner'})
    for item in item_inner :
        title = item.find('h2', {'class': 'title'})
        print(title.text.strip())

这是收到的输出:

#Breaking SI Exam Scam: Dibon Deka Arrested
Is Assam Winning the Coronavirus Fight?
Suspended RS MPs Stage Protest in Parliament
HPC Liquidator Plea For Liquidation Of Mills
Will Assam See More Than 3000 COVID Deaths?
Shiladitya ‘made’ into the Time magazine
#EXCLUSIVE Ranjan Gogoi dismissed Tarun Gogoi claim
Ravi out, IB in to get Naga Talk back on track
Traceback (most recent call last):
  File "c:\Users\Zed\Desktop\My Python Projects\random_stuffs\pratidintime.py", line 14, in <module>
    print(title.text.strip())
AttributeError: 'NoneType' object has no attribute 'text'

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    将您的 for 循环更改为

    title = item.find('h2', {'class': 'title'})
    if title is not None:
            print(title.text.strip())
    

    这应该可以避免错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多