零基础玩转天气数据抓取(手把手实战教学)

一、为什么要爬天气数据?(比你想的更有趣!)

最近帮朋友做农业数据分析时,突然发现天气数据真是块宝藏!无论是做旅游路线规划、外卖配送预测,还是农作物生长分析,都离不开准确的天气数据。关键这些数据网上都有现成的,不用白不用啊!(手动狗头)

二、新手装备清单(超简单配置)

先打开你们的命令行(Windows小伙伴按Win+R输入cmd):
bash
pip install requests beautifulsoup4 pandas
这三个库就够用了!requests负责网络请求,BeautifulSoup解析网页,pandas处理数据表格。(安装慢的可以用清华镜像源:-i https://pypi.tuna.tsinghua.edu.cn/simple)

三、实战中国天气网(附详细解剖图)

以北京天气为例,目标网址:
http://www.weather.com.cn/weather/101010100.shtml

按F12打开开发者工具,看到这个结构了吗?(见图1)每个标签藏着当天的:
- 日期(标签)
- 天气状况()
- 温度范围()
- 风力风向()

四、手撸代码环节(含防封技巧)
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
重点!!一定要加headers模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = 'http://www.weather.com.cn/weather/101010100.shtml'
超时设置很重要!避免程序卡死
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8' # 解决中文乱码
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = []
精准定位目标数据
for item in soup.select('ul[class="t clearfix"] li'):
date = item.select('h1')[0].text
weather = item.select('p[class="wea"]')[0].text
temp = item.select('p[class="tem"]')[0].text.strip()
wind = item.select('p[class="win"] i')[0].text
weather_list.append({
'日期': date,
'天气': weather,
'温度': temp,
'风力': wind
})

转成DataFrame更方便处理
df = pd.DataFrame(weather_list)
df.to_excel('北京天气.xlsx', index=False)
print('数据抓取成功!快去查看excel文件吧~')
```
五、你可能遇到的坑(血泪经验总结)

403禁止访问:一定要加headers!很多网站会拦截没有User-Agent的请求
数据抓取不全:检查CSS选择器是否写错,用select调试单个元素
突然被封IP:加上time.sleep(2) 在循环里,温柔点访问
中文乱码:除了设置encoding,还要注意网页meta标签的编码声明

六、数据可视化进阶(3行代码出图)
在代码最后追加:
```python
import matplotlib.pyplot as plt
把温度拆分成最高温和最低温
df['最高温'] = df['温度'].str.extract('(\d+)℃').astype(int)
df['最低温'] = df['温度'].str.extract('/-?(\d+)℃').astype(int)
画折线图
plt.style.use('seaborn') # 这个样式超好看!
df.plot(x='日期', y=['最高温', '最低温'], kind='line', marker='o')
plt.title('北京近期温度变化趋势')
plt.ylabel('温度(℃)')
plt.savefig('weather.png')
```

七、法律红线别碰!(重要提醒)

查看网站robots.txt(在域名后加/robots.txt)
不要高频访问(建议间隔3秒以上)
商用数据务必获得授权
遇到验证码网站建议换数据源

八、还能怎么玩?(扩展思路)

接入微信机器人定时推送天气
结合历史数据预测天气变化
制作旅游城市天气对比图
接入智能家居自动关窗(下雨预警)

下次可以试试用selenium抓动态加载的数据,或者用scrapy框架做分布式爬虫。有问题的欢迎评论区交流,看到都会回复!(代码文件已上传Github,需要的小伙伴私信获取)

标签)
- 天气状况()
- 温度范围()
- 风力风向()

四、手撸代码环节(含防封技巧)
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
重点!!一定要加headers模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = 'http://www.weather.com.cn/weather/101010100.shtml'
超时设置很重要!避免程序卡死
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8' # 解决中文乱码
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = []
精准定位目标数据
for item in soup.select('ul[class="t clearfix"] li'):
date = item.select('h1')[0].text
weather = item.select('p[class="wea"]')[0].text
temp = item.select('p[class="tem"]')[0].text.strip()
wind = item.select('p[class="win"] i')[0].text
weather_list.append({
'日期': date,
'天气': weather,
'温度': temp,
'风力': wind
})

转成DataFrame更方便处理
df = pd.DataFrame(weather_list)
df.to_excel('北京天气.xlsx', index=False)
print('数据抓取成功!快去查看excel文件吧~')
```
五、你可能遇到的坑(血泪经验总结)

403禁止访问:一定要加headers!很多网站会拦截没有User-Agent的请求
数据抓取不全:检查CSS选择器是否写错,用select调试单个元素
突然被封IP:加上time.sleep(2) 在循环里,温柔点访问
中文乱码:除了设置encoding,还要注意网页meta标签的编码声明

六、数据可视化进阶(3行代码出图)
在代码最后追加:
```python
import matplotlib.pyplot as plt
把温度拆分成最高温和最低温
df['最高温'] = df['温度'].str.extract('(\d+)℃').astype(int)
df['最低温'] = df['温度'].str.extract('/-?(\d+)℃').astype(int)
画折线图
plt.style.use('seaborn') # 这个样式超好看!
df.plot(x='日期', y=['最高温', '最低温'], kind='line', marker='o')
plt.title('北京近期温度变化趋势')
plt.ylabel('温度(℃)')
plt.savefig('weather.png')
```

七、法律红线别碰!(重要提醒)

查看网站robots.txt(在域名后加/robots.txt)
不要高频访问(建议间隔3秒以上)
商用数据务必获得授权
遇到验证码网站建议换数据源

八、还能怎么玩?(扩展思路)

接入微信机器人定时推送天气
结合历史数据预测天气变化
制作旅游城市天气对比图
接入智能家居自动关窗(下雨预警)

下次可以试试用selenium抓动态加载的数据,或者用scrapy框架做分布式爬虫。有问题的欢迎评论区交流,看到都会回复!(代码文件已上传Github,需要的小伙伴私信获取)


- 温度范围()
- 风力风向()

四、手撸代码环节(含防封技巧)
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
重点!!一定要加headers模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = 'http://www.weather.com.cn/weather/101010100.shtml'
超时设置很重要!避免程序卡死
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8' # 解决中文乱码
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = []
精准定位目标数据
for item in soup.select('ul[class="t clearfix"] li'):
date = item.select('h1')[0].text
weather = item.select('p[class="wea"]')[0].text
temp = item.select('p[class="tem"]')[0].text.strip()
wind = item.select('p[class="win"] i')[0].text
weather_list.append({
'日期': date,
'天气': weather,
'温度': temp,
'风力': wind
})

转成DataFrame更方便处理
df = pd.DataFrame(weather_list)
df.to_excel('北京天气.xlsx', index=False)
print('数据抓取成功!快去查看excel文件吧~')
```
五、你可能遇到的坑(血泪经验总结)

403禁止访问:一定要加headers!很多网站会拦截没有User-Agent的请求
数据抓取不全:检查CSS选择器是否写错,用select调试单个元素
突然被封IP:加上time.sleep(2) 在循环里,温柔点访问
中文乱码:除了设置encoding,还要注意网页meta标签的编码声明

六、数据可视化进阶(3行代码出图)
在代码最后追加:
```python
import matplotlib.pyplot as plt
把温度拆分成最高温和最低温
df['最高温'] = df['温度'].str.extract('(\d+)℃').astype(int)
df['最低温'] = df['温度'].str.extract('/-?(\d+)℃').astype(int)
画折线图
plt.style.use('seaborn') # 这个样式超好看!
df.plot(x='日期', y=['最高温', '最低温'], kind='line', marker='o')
plt.title('北京近期温度变化趋势')
plt.ylabel('温度(℃)')
plt.savefig('weather.png')
```

七、法律红线别碰!(重要提醒)

查看网站robots.txt(在域名后加/robots.txt)
不要高频访问(建议间隔3秒以上)
商用数据务必获得授权
遇到验证码网站建议换数据源

八、还能怎么玩?(扩展思路)

接入微信机器人定时推送天气
结合历史数据预测天气变化
制作旅游城市天气对比图
接入智能家居自动关窗(下雨预警)

下次可以试试用selenium抓动态加载的数据,或者用scrapy框架做分布式爬虫。有问题的欢迎评论区交流,看到都会回复!(代码文件已上传Github,需要的小伙伴私信获取)


- 风力风向()

四、手撸代码环节(含防封技巧)
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
重点!!一定要加headers模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = 'http://www.weather.com.cn/weather/101010100.shtml'
超时设置很重要!避免程序卡死
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8' # 解决中文乱码
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = []
精准定位目标数据
for item in soup.select('ul[class="t clearfix"] li'):
date = item.select('h1')[0].text
weather = item.select('p[class="wea"]')[0].text
temp = item.select('p[class="tem"]')[0].text.strip()
wind = item.select('p[class="win"] i')[0].text
weather_list.append({
'日期': date,
'天气': weather,
'温度': temp,
'风力': wind
})

转成DataFrame更方便处理
df = pd.DataFrame(weather_list)
df.to_excel('北京天气.xlsx', index=False)
print('数据抓取成功!快去查看excel文件吧~')
```
五、你可能遇到的坑(血泪经验总结)

403禁止访问:一定要加headers!很多网站会拦截没有User-Agent的请求
数据抓取不全:检查CSS选择器是否写错,用select调试单个元素
突然被封IP:加上time.sleep(2) 在循环里,温柔点访问
中文乱码:除了设置encoding,还要注意网页meta标签的编码声明

六、数据可视化进阶(3行代码出图)
在代码最后追加:
```python
import matplotlib.pyplot as plt
把温度拆分成最高温和最低温
df['最高温'] = df['温度'].str.extract('(\d+)℃').astype(int)
df['最低温'] = df['温度'].str.extract('/-?(\d+)℃').astype(int)
画折线图
plt.style.use('seaborn') # 这个样式超好看!
df.plot(x='日期', y=['最高温', '最低温'], kind='line', marker='o')
plt.title('北京近期温度变化趋势')
plt.ylabel('温度(℃)')
plt.savefig('weather.png')
```

七、法律红线别碰!(重要提醒)

查看网站robots.txt(在域名后加/robots.txt)
不要高频访问(建议间隔3秒以上)
商用数据务必获得授权
遇到验证码网站建议换数据源

八、还能怎么玩?(扩展思路)

接入微信机器人定时推送天气
结合历史数据预测天气变化
制作旅游城市天气对比图
接入智能家居自动关窗(下雨预警)

下次可以试试用selenium抓动态加载的数据,或者用scrapy框架做分布式爬虫。有问题的欢迎评论区交流,看到都会回复!(代码文件已上传Github,需要的小伙伴私信获取)

四、手撸代码环节(含防封技巧)

```python
import requests
from bs4 import BeautifulSoup
import pandas as pd

重点!!一定要加headers模拟浏览器

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}

url = 'http://www.weather.com.cn/weather/101010100.shtml'

超时设置很重要!避免程序卡死

response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8' # 解决中文乱码

soup = BeautifulSoup(response.text, 'html.parser')
weather_list = []

精准定位目标数据

for item in soup.select('ul[class="t clearfix"] li'):
date = item.select('h1')[0].text
weather = item.select('p[class="wea"]')[0].text
temp = item.select('p[class="tem"]')[0].text.strip()
wind = item.select('p[class="win"] i')[0].text

转成DataFrame更方便处理

df = pd.DataFrame(weather_list)
df.to_excel('北京天气.xlsx', index=False)
print('数据抓取成功!快去查看excel文件吧~')
```

五、你可能遇到的坑(血泪经验总结)

  1. 403禁止访问:一定要加headers!很多网站会拦截没有User-Agent的请求
  2. 数据抓取不全:检查CSS选择器是否写错,用select调试单个元素
  3. 突然被封IP:加上time.sleep(2) 在循环里,温柔点访问
  4. 中文乱码:除了设置encoding,还要注意网页meta标签的编码声明

六、数据可视化进阶(3行代码出图)

在代码最后追加:
```python
import matplotlib.pyplot as plt

把温度拆分成最高温和最低温

df['最高温'] = df['温度'].str.extract('(\d+)℃').astype(int)
df['最低温'] = df['温度'].str.extract('/-?(\d+)℃').astype(int)

画折线图

plt.style.use('seaborn') # 这个样式超好看!
df.plot(x='日期', y=['最高温', '最低温'], kind='line', marker='o')
plt.title('北京近期温度变化趋势')
plt.ylabel('温度(℃)')
plt.savefig('weather.png')
```

七、法律红线别碰!(重要提醒)

  • 查看网站robots.txt(在域名后加/robots.txt)
  • 不要高频访问(建议间隔3秒以上)
  • 商用数据务必获得授权
  • 遇到验证码网站建议换数据源

八、还能怎么玩?(扩展思路)

  1. 接入微信机器人定时推送天气
  2. 结合历史数据预测天气变化
  3. 制作旅游城市天气对比图
  4. 接入智能家居自动关窗(下雨预警)

下次可以试试用selenium抓动态加载的数据,或者用scrapy框架做分布式爬虫。有问题的欢迎评论区交流,看到都会回复!(代码文件已上传Github,需要的小伙伴私信获取)

posted @ 2025-05-15 21:05  小飞技术快餐  阅读(3)  评论(0)    收藏  举报