温馨提示×

python怎么爬取天气数据

小亿
97
2023-08-31 04:14:40
栏目: 编程语言

要爬取天气数据,你可以使用 Python 中的第三方库如 requests 和 BeautifulSoup。以下是一个简单的示例,演示如何使用这些库来爬取天气数据:

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--3KcTQ'}).text
condition = data.find('div', {'class': 'CurrentConditions--phraseValue--2Z18W'}).text
print('Temperature:', temperature)
print('Condition:', condition)

这只是一个简单的示例,具体的爬取方法可能会因网站结构的变化而有所不同。你可以根据目标网站的结构和需要爬取的内容来调整代码。

0