python天气爬虫代码
时间: 2023-10-30 08:02:58 浏览: 76
以下是一个简单的Python天气爬虫代码,可以获取指定城市的天气情况:
```python
import requests
from bs4 import BeautifulSoup
city = input("请输入城市名:")
url = f"http://www.weather.com.cn/weather/{city}.shtml"
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)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = soup.select(".t .clearfix")
for weather in weather_list:
date = weather.select(".week")[0].text
weather_desc = weather.select(".wea")[0].text
temperature = weather.select(".tem")[0].text
print(date, weather_desc, temperature)
```
使用时只需要输入指定城市,即可输出该城市未来七天的天气情况。需要注意的是,该代码依赖于requests和BeautifulSoup库,请确保这两个库已经安装。
阅读全文