当前位置: 首页>编程语言>正文

python爬取历史天气数据

原文链接:

环境说明

扒取的网站:天气网,http://lishi.tianqi.com/

Python版本:2.7

操作系统:windows 7

所依赖的包(如若没有请安装)

包名说明官方地址

bs4是一个可以从HTML或XML文件中提取数据的Python库https://pypi.python.org/pypi/requests/

requests基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库https://pypi.python.org/pypi/requests/

xlwt本文中将获取得到的天气数据存储在xls中,需要对excel进行处理的包https://pypi.python.org/pypi/xlwt

# -*- coding=utf-8 -*-

from bs4 import BeautifulSoup

import requests import xlwt import os#获得某一个月的天气数据

defgetListByUrl(url):

res = requests.get(url)

soup = BeautifulSoup(res.text,"html.parser")

weathers = soup.select("#tool_site")

title = weathers[1].select("h3")[0].text

weatherInfors = weathers[1].select("ul")

weatherList = list()forweatherInforinweatherInfors:

singleWeather = list()forliinweatherInfor.select('li'):

singleWeather.append(li.text)

weatherList.append(singleWeather)

print(title)returnweatherList,title#@par:addressUrl 获得某地区的数据#@par:excelSavePath? 数据的保存地址defgetListByAddress(addressUrl,excelSavePath):# url = "http://lishi.tianqi.com/beijing/index.html"url = addressUrl

res = requests.get(url)

soup = BeautifulSoup(res.text,"html.parser")

dates = soup.select(".tqtongji1 ul li a")

workbook = xlwt.Workbook(encoding='utf-8')fordindates:

weatherList,title = getListByUrl(d["href"])

booksheet = workbook.add_sheet(title,cell_overwrite_ok=True)fori,rowinenumerate(weatherList):forj,colinenumerate(row):

booksheet.write(i,j,col)

workbook.save(excelSavePath)if__name__ =="__main__":

addressName = raw_input("请输入即将获取天气的城市:\n")

addresses = BeautifulSoup(requests.get('http://lishi.tianqi.com/').text,"html.parser")

queryAddress = addresses.find_all('a',text=addressName)iflen(queryAddress):

savePath = raw_input("检测到有该城市数据,请输入即将保存天气数据的路径(如若不输入,将默认保存到c:/weather/"+addressName+".xls):\n")ifnotsavePath.strip():ifnotos.path.exists('c:/weather'):

os.makedirs('c:/weather')

savePath ="c:/weather/"+addressName+".xls"forqinqueryAddress:

getListByAddress(q["href"],savePath)

print("已经天气数据保存到:"+savePath)else:

print("不存在该城市的数据")

本代码是在windows下编辑的,如若想要在Linux下运行,请在头部加上#! python环境


本代码功能描述:

输入:

城市名称,如果没有则提示“不存在该城市的数据”

保存路径,如果不输入则默认保存在“c:/weather/城市名称.xls”

输出:

带有该城市的天气数据

代码演示

本程序是在pycharm IDE下开发的,直接利用pycharm执行,大家可以用别的编辑器来执行(注意,由于编码问题,如果直接用dos来执行会报错)

将getWeatherByQuery.py文件导入到pycharm下执行,如下图所示:

python爬取历史天气数据,第1张

按照提示,输入城市,检测到有该城市,请求输入保存路径

python爬取历史天气数据,第2张

在这里我们输入要保存的路径(当然也可以直接回车),在这里我输入“d:\weather\bj.xls”(请确保该目录存在,因为程序不会自动去创建目录)

python爬取历史天气数据,第3张

此时程序会将各月份的数据导出

python爬取历史天气数据,第4张

执行完之后结果如下图:

python爬取历史天气数据,第5张

excel中的数据如下图:

python爬取历史天气数据,第6张

https://www.xamrdz.com/lan/55p1848905.html

相关文章: