【爬蟲】獲取新鄭機場出租車實時數據

原文鏈接:http://www.changxuan.top/?p=463


八月十五的晚上,一個同學來找我要機場出租車的數據!Excuse me,我們不生產數據、只做數據的搬運工 。

隨後我在各大平臺上都沒找到合適的數據集,找到一些之前其他比賽的數據集,但是針對特定機場的出租車數據除了“飛常準”上有一份浦東機場的就沒找到別的!想想也是,誰沒事統計這個東西!不過知乎上的大神就是多啊,我找着找着看到一個人給了個鏈接:

 http://www.whalebj.com/xzjc/default.aspx?tdsourcetag=s_pctim_aiomsg 

打開後如下圖所示,
在這裏插入圖片描述
看樣子這個數據應該可以應付一下了!在頻繁的刷新網頁之後,初步判斷沒有反爬蟲措施就馬上打開 PyCharm 開始寫程序(寫的倉促,能跑即可)

import requests
from lxml import etree
import time
import csv
import re
header = ['時間', '場內待運車輛數', '前半小時進場車輛數', '前半小時離場車輛數']
with open('./taxi_info_xzjc.csv', encoding='UTF-8', mode='w') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(header)
f.close()
 
headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
}
 
def save_data(data):
    with open('./taxi_info_xzjc.csv', encoding='UTF-8', mode='a+') as f:
        f_csv = csv.writer(f)
        f_csv.writerow(data)
    f.close()
def get_info(url):
    res = requests.get(url, headers=headers)
    if res.status_code == 200:
        selector = etree.HTML(res.text)
        at_time = selector.xpath('//*[@id="Label_Msg"]/text()[3]')[0][7:].rstrip(')').lstrip()
        car_num_in_room = selector.xpath('//*[@id="Label_Msg"]/text()[5]')[0]
        car_num_in_room_num = re.search(r"\d+", car_num_in_room).group()
        before_half_hour_in_car = selector.xpath('//*[@id="Label_Msg"]/text()[7]')[0]
        before_half_hour_in_car_num = re.search(r"\d+", before_half_hour_in_car).group()
        before_half_hour_out_car = selector.xpath('//*[@id="Label_Msg"]/text()[9]')[0]
        before_half_hour_out_car_num = re.search(r"\d+", before_half_hour_out_car).group()
        tup = (at_time, car_num_in_room_num, before_half_hour_in_car_num, before_half_hour_out_car_num)
        save_data(tup)
 
 
if __name__ == '__main__':
    url = "http://www.whalebj.com/xzjc/default.aspx?tdsourcetag=s_pctim_aiomsg"
    while 1:
        get_info(url)
        time.sleep(10)

測試可以抓取數據之後,便扔到服務器上執行下面的命令,便可以安心睡覺了!

setsid python -u getTaxiInfo.py > run.log 2>&1

第二天早晨,查看一下結果:
在這裏插入圖片描述


微信訂閱號

——Worldhello 給你說些好玩的事情
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章