给我一个爬取天气数据的Python程序
时间: 2024-03-18 12:44:23 浏览: 18
好的,以下是一个爬取天气数据的Python程序示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.weather.com.cn/weather/101010100.shtml' # 北京天气预报网址
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
weather = soup.find(class_='wea')
temp = soup.find(class_='tem')
wind = soup.find(class_='win')
print('天气:', weather.string)
print('温度:', temp.string + '℃')
print('风力:', wind.string)
```
这个程序会爬取中国天气网的北京天气预报页面,并输出天气、温度、风力等信息。你可以根据自己需要修改网址和解析方式。
相关问题
给我一个爬取天气数据的案例
当然可以!这里是一个使用CSDN开发者接口爬取天气数据的案例:
```python
import requests
def get_weather(city):
url = f'https://apis.csdn.net/common/weather/getWeather?city={city}'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'
}
response = requests.get(url, headers=headers)
data = response.json()
if data['status'] == 200:
weather_info = data['data']['forecast'][0]['type']
temperature = data['data']['forecast'][0]['high']
return f'{city}的天气为:{weather_info},最高温度:{temperature}'
else:
return '获取天气数据失败'
city = input('请输入城市名称:')
result = get_weather(city)
print(result)
```
这个案例使用了requests库来发送HTTP请求,并且调用了CSDN开发者接口获取天气数据。用户需要输入城市名称,然后程序会从CSDN开发者接口中爬取该城市的天气信息并返回显示。
注意:请确保安装了requests库,可以使用`pip install requests`命令进行安装。另外,根据需要可能需要调整headers中的User-Agent参数。
希望这个案例能对你有所帮助!如果有任何问题,请随时提问。
编写爬取天气的python程序
以下是一个简单的Python程序,可以从网站上爬取天气信息:
```python
import requests
from bs4 import BeautifulSoup
# 设置要爬取的城市和日期
city = 'beijing'
date = '2019-01-01'
# 构造URL
url = f'http://www.tianqihoubao.com/lishi/{city}/month/{date}.html'
# 发送请求,获取页面内容
res = requests.get(url)
res.encoding = 'gbk' # 设置编码为gbk,因为该网站使用gbk编码
html = res.text
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(html, 'html.parser')
# 获取表格元素
table = soup.find('table', class_='b')
# 解析表格数据,获取每天的天气信息
for tr in table.find_all('tr')[1:]:
tds = tr.find_all('td')
day = tds[0].text.strip()
desc = tds[1].text.strip()
temp = tds[2].text.strip()
wind = tds[3].text.strip()
print(f'{day} {desc} {temp} {wind}')
```
该程序使用requests库发送请求,然后使用BeautifulSoup解析页面内容,最后解析表格数据获取每天的天气信息,并打印出来。请注意,该程序只是一个示例,实际应用中需要根据具体情况进行修改。