pycharmt提取天气预报
时间: 2023-07-02 08:24:23 浏览: 79
提取天气预报需要先确定数据源和提取方式。以下是一个基于 Python3 和 BeautifulSoup4 库的示例代码,可以从中国天气网获取天气预报信息:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,避免被网站反爬虫机制拦截
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'}
# 获取天气预报页面的 HTML 代码
url = 'http://www.weather.com.cn/weather/101010100.shtml'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# 提取天气预报信息
city = soup.select('.crumbs.fl a')[-1].text.strip() # 城市
date = soup.select('.today em')[0].text.strip() # 日期
temperature = soup.select('.tem span') # 温度
weather = soup.select('.wea') # 天气
# 打印天气预报信息
print(f'{city} {date} {temperature[0].text.strip()} {weather[0].text.strip()}')
```
这段代码可以提取北京市的天气预报信息,并打印出来,可以根据需要进行修改。需要注意的是,该网站的 HTML 结构可能会随时更改,代码也需要随之调整。