【问题标题】:AttributeError: 'NoneType' object has no attribute 'get_text'. Why am I receiving this error? [duplicate]AttributeError:“NoneType”对象没有属性“get_text”。为什么我会收到此错误? [复制]
【发布时间】:2020-01-08 16:51:12
【问题描述】:

我能够成功抓取该网站,但现在无法正常工作。我现在收到“温度”变量的错误。

这些变量有效...

period_names = [item.find(class_='period-name').get_text() for item in items]

short_descriptions = [item.find(class_='short-desc').get_text() for item in items]

这个变量以前可以工作……现在不行了。

temperatures = [item.find(class_='temp').get_text() for item in items]

这是我的代码:

import requests
from bs4 import BeautifulSoup
page = requests.get('https://forecast.weather.gov/MapClick.php? 
lat=34.05349000000007&lon=-118.24531999999999#.XV8stehKg2w')
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-body')
items = (week.find_all(class_= 'tombstone-container'))

period_names = [item.find(class_='period-name').get_text() for item in 
items]
short_descriptions = [item.find(class_='short-desc').get_text() for item 
in items]
temperatures = [item.find(class_='temp').get_text() for item in items]

print(temperatures)

我希望代码能够打印出每天的温度,因为它过去一直有效。相反,我收到了 AttributeError 消息:

  File "C:\Users\Administrator\PycharmProjects\giraffe\apps.py", line 97, 
in <listcomp>
    temperatures = [item.find(class_='temp').get_text() for item in items]
AttributeError: 'NoneType' object has no attribute 'get_text'

【问题讨论】:

  • 你得到了那个错误,因为在某个时候item.find(class_='temp') 给了None

标签: python parsing web-scraping


【解决方案1】:

你试过了吗:

temperatures = [item.find(class_='temp').get_text() if item.find(class_='temp') is not None else "" for item in items]

如果您的查找返回 None,这将返回一个空字符串

【讨论】:

  • 效果很好...非常感谢!
  • @AbleArcher 请接受答案,以便未来的用户知道这个答案是正确的。
猜你喜欢
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
相关资源
最近更新 更多