背景
架空线路常见的故障有:风偏闪络故障、雷击跳闸故障、雷击断股故障、线路覆冰故障、线路污闪故障、线路外力破坏故障、线路鸟害故障等等。从这些故障中,我们可以看出天气对线路的安全运行起到非常重要的作用。
在上一篇图文 如何爬取一个地区的气象数据(上)中我们介绍了构造一个时间区段的方法,今天我们一起来爬取 给定时间区段和地区的 气象数据的方法。
技术分析
首先,我们来观察一下请求数据的url
地址。
本次爬取数据的区域为邯郸、衡水、保定、沧州、石家庄、邢台,也就是河北电力公司所管辖区域的气象数据。
邯郸地区:
2019年08月份~2019年10月份数据的url
地址:
- http://lishi.tianqi.com/handan/201908.html
- http://lishi.tianqi.com/handan/201909.html
- http://lishi.tianqi.com/handan/201910.html
衡水地区:
2019年08月份~2019年10月份数据的url
地址:
- http://lishi.tianqi.com/hengshui/201908.html
- http://lishi.tianqi.com/hengshui/201909.html
- http://lishi.tianqi.com/hengshui/201910.html
保定地区:
2019年08月份~2019年10月份数据的url
地址:
- http://lishi.tianqi.com/baoding/201908.html
- http://lishi.tianqi.com/baoding/201909.html
- http://lishi.tianqi.com/baoding/201910.html
以此类推,我们可以发现url
中有两个参数第一个参数表示城市,另一个表示时间(年月)。
其次,我们用Python来实现这次的数据爬取任务。
lsgodatetime
模块,在上一篇图文中介绍过。requests
模块,用于发送网络请求并接收返回的数据。lxml
模块,用于解析和处理网页数据。
有关requests
模块的使用方法,以及lxml
中关于xpath
和etree
的使用方法,我会另外写一篇图文来详细介绍。这里就不详细介绍了。
代码实现
import requests
from lxml import etree
import lsgodatetime
def getData(city, date):
'''
:param city: 城市
:param date: 日期“年月”
:return: 该城市在该年月的气象数据列表
'''
lst = []
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}
url = "http://lishi.tianqi.com/{0}/{1}.html".format(city, date)
html = requests.get(url, headers=headers)
bs = etree.HTML(html.text)
text = bs.xpath('//ul[@class="lishitable_content clearfix"]/li/div/text()')
# 201205 之后网页规则发生变化
text1 = bs.xpath('//ul[@class="lishitable_content clearfix"]/li/div/a/text()')
if text1:
i, j = 0, 0
while i < len(text1):
date = text1[i]
high = text[j + 0]
low = text[j + 1]
weather = text[j + 2]
wind = text[j + 3]
data = "{0},{1},{2},{3},{4}{5}".format(date, high, low, weather, wind, '\n')
i = i + 1
j = j + 4
lst.append(data)
else:
i = 0
while i < len(text):
date = text[i + 0]
high = text[i + 1]
low = text[i + 2]
weather = text[i + 3]
wind = text[i + 4]
data = "{0},{1},{2},{3},{4}{5}".format(date, high, low, weather, wind, '\n')
i = i + 5
lst.append(data)
return lst
if __name__ == '__main__':
months = lsgodatetime.getBetweenMonth('20110201', '20191001')
lst = []
citys = tuple(['handan', 'hengshui', 'baoding', 'cangzhou', 'shijiazhuang', 'xingtai'])
for city in citys:
for item in months:
lst.extend(getData(city, item))
f = open('{0}.csv'.format(city), 'w+')
f.writelines(lst)
f.seek(0, 0)
for each in f:
print(each)
f.close()
总结
本文详细介绍了利用Python爬取气象数据的方法。这个只是做架空线路气象灾害风险分析的开始,后面还有很多的工作要做。今天就到这里吧!See You!
往期活动
LSGO软件技术团队会定期开展提升编程技能的刻意练习活动,希望大家能够参与进来一起刻意练习,一起学习进步!