Python爬虫实战:获取成都市未来15天天气预报

本教程将带你使用Python和BeautifulSoup库,编写一个简单的网络爬虫,从中国天气网抓取成都市未来15天的天气预报数据。

1. 准备工作

  • 确保你的电脑上已经安装了Python环境。
  • 使用pip安装必要的库:
pip install requests beautifulsoup4

2. 编写代码

import requests
from bs4 import BeautifulSoup

# 发送请求获取网页内容
res = requests.get('http://www.weather.com.cn/weather15d/101270101.shtml')
res.encoding = 'utf-8'
html = res.text

# 使用BeautifulSoup解析网页
soup = BeautifulSoup(html, 'html.parser')

# 提取天气数据
weathers = soup.select('#15d .t .clearfix li')
for weather in weathers:
    weather_date = weather.find('span', class_='time').text
    weather_wea = weather.find('span', class_='wea').text
    weather_tem = weather.find('span', class_='tem').text
    weather_wind = weather.find('span', class_='wind').text
    weather_wind1 = weather.find('span', class_='wind1').text
    
    # 格式化输出结果
    result = '日期: ' + weather_date + ', 天气: ' + weather_wea + ', 温度: ' + weather_tem + ', 风力: ' + weather_wind + weather_wind1
    print(result)

3. 运行代码

将以上代码保存为.py文件,例如weather_spider.py,然后在终端中运行:

python weather_spider.py

程序将会输出成都市未来15天的天气预报信息。

代码解析:

  • 首先,我们使用requests库发送HTTP请求获取网页内容。
  • 然后,使用BeautifulSoup库解析网页结构,找到包含天气信息的HTML元素。
  • 接着,使用findselect方法定位到具体的日期、天气、温度和风力等信息。
  • 最后,将提取到的信息格式化输出。

注意:

  • 网站结构可能会发生变化,导致代码失效。
  • 爬取网站数据时请遵守robots协议。

希望这篇教程能够帮助你学习如何使用Python爬取天气预报信息。

Python爬虫实战:获取成都市未来15天天气预报

原文地址: https://www.cveoy.top/t/topic/OkY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录