利用python爬虫获取天气信息
目标网站:2345天气预报网https://lishi.tianqi.com/
目标数据:北京2024年2024全年天气预报数据
在虚拟环境下:
##1.导入依赖库
import requests # 用于发送HTTP请求,获取网页内容
from bs4 import BeautifulSoup # 用于解析HTML文档,提取数据
import pandas as pd # 用于将数据保存为CSV文件
#——————————————————设置访问headers——————————————————————
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Connection': 'keep-alive',
'Referer': 'https://tianqi.2345.com/',
'Cookie': 'your_cookie_here',
}
year=2024
month=1
data=[]
for month in range(1,13):
#设置请求的url
url = 'https://tianqi.2345.com/Pc/GetHistory?areaInfo%5BareaId%5D=54511&areaInfo%5BareaType%5D=2&date%5B' \
'year%5D='+str(year)+'&date%5Bmonth%5D='+str(month)
#发送get请求
response=requests.get(url,headers=headers)
#解析json数据
json_data=response.json()
#获取嵌套在json中的html内容
html_content=json_data['data']
#对html内容进行转义处理
html_content=html_content.replace('\\"','"').replace('\\/','/').replace('\\n','')
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(html_content, 'html.parser')
# 提取表格数据
table = soup.find('table', class_='history-table')
rows = table.find_all('tr')
# 处理每一行数据
for row in rows[1:]: # 忽略标题行
cells = row.find_all('td')
# 确保行中有足够的单元格
if len(cells) >= 6:
date = cells[0].text.strip()
high_temp = cells[1].text.strip()
low_temp = cells[2].text.strip()
weather = cells[3].text.strip()
wind = cells[4].text.strip()
aqi = cells[5].text.strip()
else:
# 如果单元格数目不够,使用空字符串或其他合适的默认值
date = cells[0].text.strip() if len(cells) > 0 else ''
high_temp = cells[1].text.strip() if len(cells) > 1 else ''
low_temp = cells[2].text.strip() if len(cells) > 2 else ''
weather = cells[3].text.strip() if len(cells) > 3 else ''
wind = cells[4].text.strip() if len(cells) > 4 else ''
aqi = '' # 默认空字符串
data.append([date, high_temp, low_temp, weather, wind, aqi])
# 将数据转换为Pandas DataFrame
df = pd.DataFrame(data, columns=['日期', '最高温度', '最低温度', '天气', '风力风向', '空气质量指数'])
file_name = f'weather_data_{year}.csv' # 导出为csv文件
df.to_csv(file_name, index=False) #将文件保存到当前工作目录下
从kaggle网站下载数据集
网址:https://www.kaggle.com/datasets
在虚拟环境下:
import kagglehub #记得先conda install kagglehub
## 下载kaggle网站数据会到本地C:\Users\Fiary\.cache\kagglehub目录下
path1 = kagglehub.dataset_download("alejopaullier/new-york-city-weather-data-2019")
print("Path to dataset files:", path1) #返回存放数据的路径
再手动将文件移动到自己虚拟环境下的工作路径下,方便查找。
import os
print(os.getcwd()) #查看当前环境的工作路径