網絡爬蟲(二)

上一篇文章學習了正則表達式,正則表達式在提取爬取的json信息時,非常有效。
先跳過爬蟲爬網絡的原理,直接舉例一個簡單的爬取數據然後進行處理的例子:
獲取URL數據(北京地鐵數據):http://map.amap.com/service/subway?_1469083453978&srhdata=1100_drw_beijing.json

import requests
import re
r = requests.get('http://map.amap.com/service/subway?_1469083453978&srhdata=1100_drw_beijing.json')

request是一個http的請求庫,可以方便地發送http請求,也方便處理響應結果。
re是正則表達式要使用的模塊
requests.get()爲發送網址請求並獲取網址中信息

#獲得每個地點和他的位置:
#{站點名稱:(經度,緯度)}
places=re.findall('"n":"\w+"',r.text)
lat_lon=re.findall('"sl":"(\d+\.\d+,\d+\.\d+)"',r.text)
stations_info={}
for i in range(len(places)):
    place_name=re.findall('"n":"(\w+)"',places[i])[0]
    stations_info[place_name]=tuple(map(float,lat_lon[i].split(',')))

r.text把爬取的信息轉化爲字符串格式,也就是整個內容爲一個大字符串。這樣就可以使用這個則表達式進行提取想要的信息。

#獲得每個地點和他的位置:
#{站點名稱:(經度,緯度)}
places=re.findall('"n":"\w+"',r.text)
lat_lon=re.findall('"sl":"(\d+\.\d+,\d+\.\d+)"',r.text)
stations_info={}
for i in range(len(places)):
    place_name=re.findall('"n":"(\w+)"',places[i])[0]
    stations_info[place_name]=tuple(map(float,lat_lon[i].split(',')))

其中:

re.findall('"n":"\w+"',r.text)

在r.text中對正則表達式’“n”:"\w+"'進行匹配,匹配的是:
類似"n": "稻香湖路"的內容。

re.findall('"sl":"(\d+\.\d+,\d+\.\d+)"',r.text)

匹配的是r.text中的’sl’: '116.188145,40.068936’內容,這裏的括號則指的是隻返回()內的部分,匹配的內容類似:‘sl’:‘116.188145,40.068936’,但是隻提取’116.188145,40.068936’
(具體情況查看代碼的運行情況結合r.text的內容就可以發現。)
下面也是採用類似的方式,這裏的 | 表示的是或的關係,就是符串符合哪個正則表達式,都滿足被匹配條件。

#獲取{線路名稱:站點名稱}
kn=re.findall('"n":"(\w+)"|"kn":"(\w+)"',r.text)
kn.reverse()
lines_info={}
for i in kn:
    if i[0]=='':
        tem_key=i[1]
        lines_info[tem_key]=[]
    else:
        lines_info[tem_key]=lines_info[tem_key]+[i[0]]

下面的代碼就是進行數據整合一下,用於圖的繪製。

#建立鄰接鏈表dict   
neighbor_info={}
for i in lines_info:
    neighbor_info[i]=[]
    for j in range(len(lines_info[i])-1):
        neighbor_info[i]=neighbor_info[i]+\
                        [(lines_info[i][j],lines_info[i][j+1])]
import networkx as nx
import matplotlib.pyplot as plt
from pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認字體
plt.figure(figsize=(30,30))
city_graph=nx.Graph()  #新建圖類實例
city_graph.add_nodes_from(list(stations_info.keys())) #添加點

nx.draw_networkx_nodes(city_graph,stations_info,node_size=20,node_color='red')#繪製點,nodelist默認爲G中的所有節點
nx.draw_networkx_labels(city_graph,stations_info,font_size=7)
col_list=['#b45b1f','#1fb4a6','#1f2db4','#b4a61f','#78b41f','#b41f78','#b41f78','#a61fb4','#b45b1f','#2db41f','#5b1fb4','#78b41f',\
'#b45b1f','#1fb4a6','#1f2db4','#b4a61f','#78b41f','#2aa930','#b41f78','#a61fb4','#b45b1f','#2db41f','#5b1fb4','#78b41f']
for i,index in enumerate(neighbor_info):
    nx.draw_networkx_edges(city_graph,stations_info,edgelist=neighbor_info[index],width=1.5,edge_color=col_list[i])
plt.show()

最終的結果如下:
在這裏插入圖片描述
完整代碼下載:
https://github.com/ShuoLiu-Max/Web-spider

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