在我们生活的每一个天,都有天气(废话!)那我们可以使用Python的BeautifulSoup库就能爬取到天气信息。
pip install beautifulsoup4
pip install lxml
笔者是Python3.11制作的,就拿杭州的信息做:
from bs4 import BeautifulSoup
import requests
url = "http://www.weather.com.cn/weather1d/101210101.shtml"
response = requests.get(url)
response.encoding = "utf-8"
html_doc = response.text
weather_info = {"wea": None, "tem": None, "win": None}
weather = {"daytime": weather_info, "night": weather_info.copy()}
soup = BeautifulSoup(html_doc, "lxml")
print("今日信息:")
wea = soup.select('#today > div.t > ul > li:nth-child(1) > p.wea')
print("天气:"+wea[0].string)
weather['daytime']['wea'] = wea[0].string
tem = soup.select('#today > div.t > ul > li:nth-child(1) > p.tem > span')
print("温度:"+tem[0].string+"℃")
weather['daytime']['tem'] = tem[0].string
win = soup.select('#today > div.t > ul > li:nth-child(1) > p.win > span')
print("风力:"+win[0].string)
weather['daytime']['win'] = win[0].string
print("\n明日信息:")
wea = soup.select('#today > div.t > ul > li:nth-child(2) > p.wea')
print("天气:"+wea[0].string)
weather['night']['wea'] = wea[0].string
tem = soup.select('#today > div.t > ul > li:nth-child(2) > p.tem > span')
print("温度:"+tem[0].string+"℃")
weather['night']['tem'] = tem[0].string
win = soup.select('#today > div.t > ul > li:nth-child(2) > p.win > span')
print("风力:"+win[0].string)
weather['night']['win'] = win[0].string
如果是别的地区,就可以把第4行url的值改动,如北京和深圳的:
# 北京
url = "http://www.weather.com.cn/weather1d/101010100.shtml"
# 深圳
url = "http://www.weather.com.cn/weather1d/101280601.shtml"
看在作者写了这么多代码的份上,给个点赞呗!