Python抓取中国各省市天气预报数据脚本
以下是一个简单的脚本,使用了requests和BeautifulSoup库来抓取和解析网页数据。
import requests
from bs4 import BeautifulSoup
# 设置请求头,避免被网站拦截
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 获取中国天气网的城市列表
city_url = 'http://www.weather.com.cn/textFC/hb.shtml'
response = requests.get(city_url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
city_list = soup.select('#forecastID ul li a')
# 遍历城市列表,抓取天气数据
for city in city_list:
city_name = city.get_text()
city_code = city['href'][-11:-5]
weather_url = 'http://www.weather.com.cn/weather/{}.shtml'.format(city_code)
response = requests.get(weather_url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
weather_list = soup.select('.t li')
print(city_name)
for weather in weather_list:
print(weather.get_text())
print('
')
这个脚本首先获取中国天气网的城市列表,遍历列表获取每个城市的名称和代码,然后根据代码拼接出对应的天气预报页面URL,再次发送请求获取页面内容。最后使用BeautifulSoup解析页面,提取出所需的天气数据并打印到控制台上。
需要注意的是,由于中国天气网的反爬虫机制比较强,因此我们需要设置请求头来模拟浏览器访问。另外,由于该网站的页面结构可能会发生变化,因此代码可能需要根据实际情况做一些调整。
原文地址: https://www.cveoy.top/t/topic/nLFc 著作权归作者所有。请勿转载和采集!