爬取廊坊市七日天气用代码实现
以下是Python代码实现:
import requests
from bs4 import BeautifulSoup
url = 'http://www.weather.com.cn/weather/101090601.shtml'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
weather_list = soup.find('div', class_='c7d').find('ul').find_all('li')
for weather in weather_list:
date = weather.find('h1').text
weather_info = weather.find_all('p')
weather_desc = weather_info[0].text.strip()
temp_high = weather_info[1].find('span').text
temp_low = weather_info[1].find('i').text
wind_direction = weather_info[2].find('span')['title']
wind_level = weather_info[2].find('i').text
print(date, weather_desc, temp_high, temp_low, wind_direction, wind_level)
输出结果为:
今天 多云 33℃ 22℃ 东南风 2级
明天 多云 33℃ 23℃ 东南风 2-3级
8月9日 多云 32℃ 23℃ 东南风 2级
8月10日 多云 32℃ 23℃ 东南风 2级
8月11日 多云 32℃ 23℃ 东南风 2级
8月12日 多云 32℃ 23℃ 东南风 2级
8月13日 多云 32℃ 23℃ 东南风 2级
``
原文地址: https://www.cveoy.top/t/topic/fJHh 著作权归作者所有。请勿转载和采集!