BeautifulSoup-'NoneType'对象没有属性'get_text'

时间:2020-08-07 10:42:46

标签: python-3.x beautifulsoup

输出显示

AttributeError:'NoneType'对象没有属性'get_text'

import requests
from bs4 import BeautifulSoup

url = requests.get('https://forecast.weather.gov/MapClick.php?lat=34.05361000000005&lon=-118.24549999999999#.Xy0hrigzaUk')

soup = BeautifulSoup(url.content,'lxml')
week = soup.find(id='seven-day-forecast-body')
items =week.find_all(class_='tombstone-container')
period = [item.find(class_='period-name').get_text() for item in items]
desc = [item.find(class_='short-desc').get_text() for item in items]
temp = [item.find(class_='temp temp-low').get_text() for item in items]
print(period)
print(desc)   
print(temp)

有人可以告诉我我在做什么错。谢谢!

1 个答案:

答案 0 :(得分:2)

您可以在列表理解if item

的每一行中添加

类似的东西:

[item.find(class_=???).get_text() for item in items if item]

错误是某些item对象实际上是None。导致此错误引发。如果您过滤None,则将是安全的。