python爬取天气预报代码
时间: 2023-11-09 20:03:30 浏览: 113
以下是一个简单的Python爬取天气预报的代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.weather.com.cn/weather/101010100.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)
soup = BeautifulSoup(response.content, 'html.parser')
weather_list = soup.select('.t li')
for weather in weather_list:
date = weather.select('.time')[0].text
detail = weather.select('.detail')[0].text
temperature = weather.select('.tem')[0].text
print(date, detail, temperature)
```
这个代码使用requests库和BeautifulSoup库来获取天气预报页面,并从页面中提取出日期、天气详情和温度信息。你可以根据自己的需要修改代码来获取更多的信息。
阅读全文