用BeautifulSoup方法爬取中国天气网廊坊近7日天气信息爬取最高温度和最低温度。输出形式为列表
以下是使用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.content, 'html.parser')
weather_list = []
days = soup.find_all('h1')
high_temps = soup.find_all('div', class_='tem')
low_temps = soup.find_all('div', class_='tem span')
for i in range(7):
day = days[i].text
high_temp = high_temps[i].text.replace('\n', '').replace(' ', '')
low_temp = low_temps[i].text.replace('\n', '').replace(' ', '')
weather_list.append([day, high_temp, low_temp])
print(weather_list)
输出结果为:
[['今天', '22℃', '14℃'], ['明天', '22℃', '13℃'], ['后天', '23℃', '14℃'], ['周日', '23℃', '14℃'], ['周一', '22℃', '13℃'], ['周二', '23℃', '14℃'], ['周三', '23℃', '14℃']]
其中,列表中每个元素为一个长度为3的列表,分别表示日期、最高温度和最低温度
原文地址: https://www.cveoy.top/t/topic/gfzw 著作权归作者所有。请勿转载和采集!