【发布时间】:2021-07-19 06:23:44
【问题描述】:
我对抓取天气网站的代码有疑问。它应该每小时更新一次,但由于某种原因,给出的数据不是网站上的当前数据;它也不会更新其数据,而是不断提供相同的数据。请帮忙!!!
另外,我需要帮助从网站上抓取天气图标。
这是我的代码:
from bs4 import BeautifulSoup
from plyer import notification
import requests
import time
if __name__ == '__main__':
while True:
def notifyMe(title, message):
notification.notify(
title = title,
message = message,
#app_icon = icon,
timeout = 7
)
try:
# site = requests.get('https://weather.com/weather/today/l/5.02,7.97?par=google')
site = requests.get('https://weather.com/en-NG/weather/today/l/4dce0117809bca3e9ecdaa65fb45961a9718d6829adeb72b6a670240e10bd8c9')
# site = requests.get('http://localhost/weather.com/weather/today/l/5.02,7.97.html')
soup = BeautifulSoup(site.content, 'html.parser')
day = soup.find(class_= 'CurrentConditions--CurrentConditions--14ztG')
location = day.find(class_='CurrentConditions--location--2_osB').get_text()
timestamp = day.find(class_='CurrentConditions--timestamp--3_-CV').get_text()
tempValue = day.find(class_='CurrentConditions--tempValue--1RYJJ').get_text()
phraseValue = day.find(class_='CurrentConditions--phraseValue--17s79').get_text()
precipValue = day.find(class_='CurrentConditions--precipValue--1RgXi').get_text()
#icon = day.find(id ='svg-symbol-cloud').get_icon()
weather = timestamp + "\n" + tempValue + " " + phraseValue + "\n" + precipValue
except requests.exceptions.ConnectionError:
location = "Couldn't get a location."
weather = "Error connecting to website."
except AttributeError:
weather = timestamp + "\n" + tempValue + " " + phraseValue
# print (weather)
notifyMe( location, weather )
time.sleep(30)
预期输出:
Uyo, 阿夸伊博姆 天气 截至 13:28 WAT 30° 多云 14:00 前有 55% 的几率下雨
【问题讨论】:
-
您的预期输出是什么。请edit您的问题并将其包括在内。
-
首先您可以在
except中打印错误以查看是否获得新数据 -except AttributeError as ex: print(ex)。如果您有AttributeError,那么它使用相同的值 - 您会看到相同的值。而且你甚至不知道你得到了错误,因为你没有显示它。 -
你可以在
while-loop 之前创建notifyMe。您不必一次又一次地创建它。 -
weather.com可能使用 JavaScript 添加元素beautifulsoup无法运行 JavaScript,您可能需要使用 Selenium 来控制可以运行 JavaScript 的真实 Web 浏览器 -
服务器可能有一些系统来检测脚本/机器人/垃圾邮件发送者/黑客并发送与您预期不同的 HTML。它还可能更改类 - 在类中使用其他随机数 - 使抓取更加困难。
标签: python web-scraping beautifulsoup python-requests