爬取重庆未来半个月天气python代码
时间: 2023-10-10 15:08:37 浏览: 116
以下是爬取重庆未来半个月天气的Python代码:
import requests
from bs4 import BeautifulSoup
# 定义爬取天气的函数
def get_weather():
url = 'https://www.tianqi.com/chongqing/'
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'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = soup.find_all(class_='tqshow1')
for item in weather_list:
date = item.find(class_='week').text
weather = item.find(class_='t1').text + ',' + item.find(class_='ico1').text
print(date, weather)
# 调用函数获取天气信息
get_weather()
阅读全文