这是一个使用Python和BeautifulSoup库爬取廊坊近7天天气情况的示例代码:

import requests
from bs4 import BeautifulSoup

url = 'http://www.weather.com.cn/weather/101090601.shtml'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

weather_list = soup.select('.t > li')
for weather in weather_list:
    date = weather.select('.time')[0].text.strip()
    weather_desc = weather.select('.wea')[0].text.strip()
    temp_range = weather.select('.tem span')[0].text.strip() + ' ~ ' + weather.select('.tem i')[0].text.strip()
    print(date, weather_desc, temp_range)

解释:

  1. 首先,我们定义了一个URL,该URL是中国天气网廊坊市的城市天气预报页面的URL。
  2. 使用requests库发送GET请求以获取页面的HTML内容。
  3. 使用BeautifulSoup解析HTML内容。
  4. 从HTML内容中选择所有类为't'的列表项元素,这些元素包含天气信息。
  5. 对于每个天气列表项,提取日期、天气描述和温度范围,并将它们打印出来。

输出示例:

2021-07-27 小雨 25℃ ~ 30℃
2021-07-28 多云 25℃ ~ 30℃
2021-07-29 小雨 25℃ ~ 29℃
2021-07-30 多云转晴 24℃ ~ 30℃
2021-07-31 晴 24℃ ~ 31℃
2021-08-01 晴 26℃ ~ 33℃
2021-08-02 多云转阴 25℃ ~ 32℃

请注意,此代码仅用于演示和学习目的,任何未经授权的网站抓取都是不合法的。

廊坊7天天气预报爬取代码 - Python和BeautifulSoup实现

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

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