租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

python怎么爬取天气数据

发布时间:2023-09-01 07:59:08

python怎样爬取天气数据

要爬取天气数据,你可使用 Python 中的第三方库如 requests 和 BeautifulSoup。以下是一个简单的示例,演示怎样使用这些库来爬取天气数据:
```python
import requests
from bs4 import BeautifulSoup
# 发送要求获得网页内容
url = 'https://www.weather.com/'
response = requests.get(url)
html_content = response.text
# 使用 BeautifulSoup 解析网页内容
soup = BeautifulSoup(html_content, 'html.parser')
# 根据网页结构提取天气数据
weather_data = soup.find_all('div', {'class': 'current-weather-card'})
# 打印天气数据
for data in weather_data:
temperature = data.find('span', {'class': 'CurrentConditions--tempValue-⑶KcTQ'}).text
condition = data.find('div', {'class': 'CurrentConditions--phraseValue-⑵Z18W'}).text
print('Temperature:', temperature)
print('Condition:', condition)
```
这只是一个简单的示例,具体的爬取方法可能会因网站结构的变化而有所区分。你可以根据目标网站的结构和需要爬取的内容来调剂代码。