1. 程式人生 > >Python爬取攜程旅遊行程資訊+GIS視覺化

Python爬取攜程旅遊行程資訊+GIS視覺化

一、需求:

        爬取攜程旅行網的“北京推薦行程”首頁的各個行程文章,將各個行程所包含的景點資訊提取出來,並匯入ArcGIS進行GIS視覺化。

二、爬取思路:

        爬取北京推薦行程主頁的各個文章的URL,然後通過該URL爬取出行程文章的資料,最後進行資訊提取,得到行程景點的相關資訊。

三、編寫程式碼:

import urllib.request
import re
import pandas as pd

#模擬瀏覽器
headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)
#行程主頁URL
baseUrl="http://you.ctrip.com/journeys/beijing1.html"
pagedata1=urllib.request.urlopen(baseUrl).read().decode("utf-8","ignore")
#行程文章的名稱與URL的提取規則
articleUrlPat='<!--整塊連結-->\r.*?<a href="(.*?)" '
articleNamePat='<dt class="ellipsis">(.*?)<'
#提取文章的名稱與URL
journeyUrl=re.compile(articleUrlPat,re.S).findall(pagedata1)
journeyName=re.compile(articleNamePat,re.S).findall(pagedata1)
x=[]
#分層爬取
for i in range(0,len(journeyUrl)):
    thisUrl="http://you.ctrip.com/"+journeyUrl[i]
    thisName=journeyName[i]
    pagedata2=urllib.request.urlopen(thisUrl).read().decode("utf-8","ignore")
    namePat='"name":"(.*?)"'
    latPat='"lng":"(.*?)"'
    lonPat='"lat":"(.*?)"'
    sightNames=re.compile(namePat,re.S).findall(pagedata2)
    sightLats=re.compile(latPat,re.S).findall(pagedata2)
    sightLons=re.compile(lonPat,re.S).findall(pagedata2)
    for j in range(0,len(sightNames)):
        sightname=sightNames[j]
        sightlat=sightLats[j]
        sightlon=sightLons[j]
        x.append([i,thisName,j,sightname,float(sightlat),float(sightlon)])
#將資料結構化儲存至規定目錄的CSV檔案中
c = pd.DataFrame(x)
c.to_csv('E:/journey.csv',encoding='utf-8-sig')

四、GIS視覺化:

1、將爬取的CSV處理後,匯入ArcMap中:

2、點集轉線,線欄位設定為field2(程式碼中的“i”變數),排序欄位設定為field4(程式碼中的“j”變數):

3、根據不同行程進行唯一值渲染: