万能的python又来造福程序员了,你想让你心爱的TA一大早就收到你体贴的天气预报吗?分分钟好感爆棚。
只需要一点python的基础就可以做下去了。
在次之前,你可能需要一个云服务器帮你持续跑代码,当然如果你能保证电脑24小时不关,也可以不适用云服务器,至于云服务器的作用和推荐可自行百度。
这里以爬取中国天气的天气为例,当然你也可以尝试爬取其他网站的天气,甚至是API(和风API等)
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
def job():#自定义爬虫函数
resp=urlopen('http://www.weather.com.cn/weather/202010100.shtml')
soup=BeautifulSoup(resp,'html.parser')
tagToday=soup.find('p',class_="tem") #第一个包含class="tem"的p标签即为存放今天天气数据的标签
try:
temperatureHigh=tagToday.span.string #有时候这个最高温度是不显示的,此时利用第二天的最高温度代替。
except AttributeError as e:
temperatureHigh=tagToday.find_next('p',class_="tem").span.string #获取第二天的最高温度代替
temperatureLow=tagToday.i.string #获取最低温度
weather=soup.find('p',class_="wea").string #获取天气
content