单个城市天气数据爬取

确定目标网页

https://www.weather.com.cn/

分析网页数据

python 12 行
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import requests
from bs4 import BeautifulSoup

myHeader = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}

url = "https://www.weather.com.cn/weather1d/101010100.shtml"

r = requests.get(url)
html = r.content.decode('utf-8')

soup = BeautifulSoup(html, "html.parser")
print(soup.find('div', class_='tem'))

筛选数据

动态查询一个城市的天气

python 4 行
1
2
3
4
北京:
https://www.weather.com.cn/weather1d/101010100.shtml
沈阳:
https://www.weather.com.cn/weather1d/101070101.shtml

url = 'https://www.weather.com.cn/weather1d/' + cityCode + '.shtml'

中国天气网城市代码大全 - 豪情云天 - 博客园

利用 JSON 数据实时构建字典:

在天气网中找到这样一个 city.js 文件,

https://j.i8tq.com/weather2020/search/city.js

这个文件中包含的就是城市和编码,但是现在是乱码

完整代码:

美化版: