Python爬虫实战:3分钟搞定全国天气数据抓取(附可视化教程)
一、为什么要爬天气数据?(超实用场景)
最近帮朋友做旅游路线规划时(别问为什么用爬虫,问就是理工男的倔强),发现天气数据对行程影响超大!传统的复制粘贴太low了,用Python爬虫5行代码就能自动获取全国340个城市天气数据,还能生成酷炫可视化图表!(文末有完整源码)
二、准备工作(小白也能懂)
1. 工具清单
- Python 3.6+(推荐用Anaconda)
- 第三方库安装(CMD运行):
bash
pip install requests beautifulsoup4 pandas pyecharts
2. 目标网站分析
推荐用「中国天气网」(www.weather.com.cn)数据全且稳定!按F12打开开发者工具,找到城市列表页:
http://www.weather.com.cn/textFC/hb.shtml
(注意:华北地区页面,其他地区替换hb为对应拼音)
三、实战四步曲(附避坑指南)
步骤1:抓取城市列表(重点!)
```python
import requests
from bs4 import BeautifulSoup
def get_city_urls():
base_url = 'http://www.weather.com.cn/textFC/{}.shtml'
regions = ['hb', 'db', 'hd', 'hz', 'hn', 'xb', 'xn'] # 七大区域
city_links = []
```
步骤2:提取天气数据(XPath太复杂?试试CSS选择器)
```python
def parse_weather(url):
response = requests.get(url)
soup = BeautifulSoup(response.content.decode('utf-8'), 'html.parser')
```
步骤3:数据存储(CSV和MySQL两种方式)
```python
CSV存储(适合新手)
import pandas as pd
def save_to_csv(data):
df = pd.DataFrame(data)
df.to_csv('weather_data.csv', index=False, encoding='utf_8_sig') # 防止中文乱码
MySQL存储(适合项目)
import pymysql
def save_to_mysql(data):
conn = pymysql.connect(host='localhost', user='root', password='123456', db='weather')
try:
with conn.cursor() as cursor:
sql = """INSERT INTO weather
(city, max_temp, min_temp, wind)
VALUES (%s, %s, %s, %s)"""
cursor.executemany(sql, [tuple(item.values()) for item in data])
conn.commit()
finally:
conn.close()
```
步骤4:数据可视化(Pyecharts真香!)
```python
from pyecharts.charts import Map
from pyecharts import options as opts
def draw_temp_map(data):
temp_data = [(item['城市'], item['最高气温']) for item in data]
```
四、完整调用流程(复制即用)
```python
if name == "main":
# 获取所有城市链接(约340个)
urls = get_city_urls()[:10] # 测试用前10个
```
五、常见问题排查(血泪经验)
- 编码问题:遇到乱码时,在请求后加上.content.decode('utf-8')
- 被封IP:添加time.sleep(random.uniform(1,3))随机延迟
- 元素定位失败:用浏览器检查元素更新CSS选择器
- 数据缺失:网站改版时需要调整解析逻辑
六、法律与道德提醒(超级重要!!!)
- 控制请求频率(每秒不超过3次)
- 仅用于学习目的
- 禁止商业用途
- 遵守网站robots.txt规定
(项目完整代码已上传Github,私信回复"天气爬虫"获取地址)
浙公网安备 33010602011771号