我能够成功抓取该网站,但现在它无法正常工作。我现在收到“温度”变量的错误。
这些变量有效...
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'
答案 0 :(得分:2)
您尝试过吗:
temperatures = [item.find(class_='temp').get_text() if item.find(class_='temp') is not None else "" for item in items]
如果您的查询返回None