要爬取天气数据,你可以使用 Python 中的第三方库如 requests 和 BeautifulSoup。以下是一个简单的示例,演示如何使用这些库来爬取天气数据:
import requestsfrom 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'}).textcondition = data.find('div', {'class': 'CurrentConditions--phraseValue--2Z18W'}).textprint('Temperature:', temperature)print('Condition:', condition)这只是一个简单的示例,具体的爬取方法可能会因网站结构的变化而有所不同。你可以根据目标网站的结构和需要爬取的内容来调整代码。

