利用如下網(wǎng)址來獲取某個城市的空氣質(zhì)量
人家本來是提供了API的娩贷,而且也有公共Token可以讓人測試,但是我覺得調(diào)人家接口有點(diǎn)不好意思碱茁,反正我只要數(shù)據(jù)裸卫,也就不占用人家的服務(wù)了(哈哈,就是把爬蟲說的這么清新脫俗)纽竣,真的墓贿,你看我最后的time.sleep(1*60)
就知道我真的不是那種惡意把人家服務(wù)器搞趴的壞人。
代碼如下
# -*- coding: utf-8 -*-
from lxml import etree
import requests
import sys
import json
import datetime
import hashlib
import time
# 指定默認(rèn)編碼方式為utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
# 從網(wǎng)站獲取空氣狀況
def get_pm(city='hangzhou'): # 輸入?yún)?shù)為城市全拼
url = 'http://pm25.in/' + city
response = requests.get(url) # 獲取指定網(wǎng)址的html
html = etree.HTML(response.text)
table_result = html.xpath('//table[@id="detail-data"]') # 獲取數(shù)據(jù)表
table = table_result[0]
head_results = table.xpath('thead/tr/th') # 獲取表頭
records = table.xpath('tbody/tr') # 獲取記錄
air_record = {} # 定義字典
air_records = [] # 定義列表
for record in records: # 遍歷記錄
for i in range(0, len(head_results)): # 遍歷字段
air_record[head_results[i].text] = record.xpath('td')[i].text
air_records.append(air_record)
air_record = {} # 清空變量的緩存
return air_records
# 加時間戳輸出文件
def file_output(text, target_dir=''):
current_time = datetime.datetime.now()
file_name = current_time.strftime('%Y%m%d%H%M') + '.json'
output_file = open(target_dir + file_name, 'w')
output_file.write(text)
output_file.close()
# 校驗(yàn)是否更新
def is_update(current, original=''):
md5_of_original = hashlib.md5(original).hexdigest()
md5_of_current = hashlib.md5(current).hexdigest()
if md5_of_current == md5_of_original:
return False
else:
return True
# 定時任務(wù)
original_records_json = '' # 對比原數(shù)據(jù)初始化
while True:
current_records = get_pm() # 獲取數(shù)據(jù)
current_records_json = json.dumps(current_records, ensure_ascii=False, indent=2) # 轉(zhuǎn)化為JSON格式
if is_update(current_records_json, original_records_json):
# file_output(current_records_json)
print datetime.datetime.now().strftime('%Y%m%d%H%M') # 時間戳
print current_records_json # 數(shù)據(jù)輸出
original_records_json = current_records_json # 對比數(shù)據(jù)更新
else:
print datetime.datetime.now().strftime('%Y%m%d%H%M')
print u'數(shù)據(jù)尚未更新'
time.sleep(1*60)
最后還是非常感謝BestApp工作室的PM25.in這個作品蜓氨,因?yàn)槲腋緵]辦法在其他網(wǎng)站找到這么方便的數(shù)據(jù)獲取方式聋袋,其實(shí)根本原因就是國家環(huán)境保護(hù)部的網(wǎng)站太亂,(冏)穴吹。