日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python爬取百度迁徙_Python爬虫抓取百度慧眼迁徙大数据(一)

發(fā)布時(shí)間:2023/12/10 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬取百度迁徙_Python爬虫抓取百度慧眼迁徙大数据(一) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

引言

百度慧眼遷徙3.0上線,在選擇某一城市的“遷出目的地”或“遷入來源地”后,即可查看該城市遷出、遷入人口的遷徙來源與遷徙時(shí)間趨勢(shì)。對(duì)城市大數(shù)據(jù)研究有所幫助。本文采取Python爬蟲抓取百度慧眼數(shù)據(jù)。

image

準(zhǔn)備工作

工具:Chrome

2.查找數(shù)據(jù)源。

使用開發(fā)者工具(F12),打開Network,搜索關(guān)鍵字json。

image

右側(cè)preview預(yù)覽,打開data內(nèi)的list,即可看到j(luò)son格式的數(shù)據(jù)。

image

3.數(shù)據(jù)解析

查找json信息后,發(fā)現(xiàn)cityrank.jsonp、provincerank.jsonp和historycurve.jsonp都是可以利用的數(shù)據(jù)。cityrank是精確到市級(jí)的數(shù)據(jù)來源,provincerank是精確到省級(jí)的數(shù)據(jù)來源,historcurve是表示該地歷史數(shù)據(jù)。本文對(duì)cityrank.jsonp、provincerank.jsonp進(jìn)行了爬取。

4.Url解析

右鍵,open in tab查看地址欄地址。 example:http://huiyan.baidu.com/migration/cityrank.jsonp?dt=province&id=330000&type=move_in&callback=jsonp_1581412681419_9173670

這里可以看到參數(shù)有dt,id,type,callback等。經(jīng)過測(cè)試,dt為選取的地點(diǎn)的行政級(jí)別。id為選取的地點(diǎn)的行政編碼,是百度內(nèi)部自己的編碼。type有move_in和move_out兩種參數(shù),對(duì)應(yīng)遷入和遷出。callback對(duì)應(yīng)的是時(shí)間戳,時(shí)間精度非常大,后文默認(rèn)分鐘級(jí)別。

5.百度城市編碼

在上一步內(nèi),最難填寫的是城市代碼,一開始猜測(cè)與郵政編碼有關(guān),后對(duì)其進(jìn)行驗(yàn)證,發(fā)現(xiàn)并不完全相同。在瀏覽了百度地圖開放平臺(tái)之后,查找到了這么一份行政區(qū)劃鄉(xiāng)鎮(zhèn)清單201910.xlsx,與省份、城市id完全吻合。并通過在線的excel轉(zhuǎn)json工具,轉(zhuǎn)換為json格式,保存為文件,方便讀取。

爬取工作

因?yàn)樯婕傲薊xcel格式的寫入,所以使用前pip install xlwr。

源代碼

import requests

import json

import time

import xlwt

def CityName2Code(dt,cityName):

"""城市名/省名轉(zhuǎn)換為編碼

Arguments:

dt {str} -- [description]

cityName {str} -- [description]

"""

cityCode=''

searchKey=''

codeKey=''

#城市編碼的相對(duì)路徑

cityCodePath ='migration/CityCode.json'

#打開文件,文件編碼格式為UTF-8

data = open((cityCodePath), encoding='utf-8')

result = json.load(data)

if dt=='province':

searchKey='省名稱'

codeKey='省代碼'

elif dt =='city':

searchKey='地級(jí)市名稱'

codeKey='地級(jí)市代碼'

for rowNum in range(len(result)):

if result[rowNum][searchKey]==cityName:

cityCode = result[rowNum][codeKey]

return cityCode

def UrlFormat(rankMethod,dt,name,migrationType,date):

"""字符串定義,默認(rèn)時(shí)間為00:00:00,精確到分鐘級(jí)別

Arguments:

rankMethod {str} -- city||province 獲得數(shù)據(jù)的行政級(jí)別

dt {str} -- city||province 中心地行政級(jí)別

name {str} -- example:'溫州市||浙江省' 作為中心地的地名

migrationType {str} -- in||out

date {str} -- example:20200202

"""

list_date = list(date)

list_date.insert(4,'-')

list_date.insert(7,'-')

formatDate = ''.join(list_date)

formatDate= formatDate+" 00:00:00"

#轉(zhuǎn)換成時(shí)間數(shù)組

timeArray = time.strptime(formatDate, "%Y-%m-%d %H:%M:%S")

#轉(zhuǎn)換成時(shí)間戳

timeUnix = time.mktime(timeArray)

ID = CityName2Code(dt,name)

url='http://huiyan.baidu.com/migration/{0}rank.jsonp?dt={1}&id={2}&type=move_{3}&date={4}&callback' \

'=jsonp_{5}000_0000000'.format(rankMethod,dt,ID,migrationType,date,int(timeUnix))

return url

#返回?cái)?shù)據(jù)處理

def JsonTextConvert(text):

"""Text2Json

Arguments:

text {str} -- webContent

Returns:

str -- jsonText

"""

text = text.encode('utf-8').decode('unicode_escape')

head, sep, tail = text.partition('(')

tail=tail.replace(")","")

return tail

def GetData(rankMethod,dt,name,migrationType,date,isExcel):

"""

Arguments:

rankMethod {str} -- city||province 獲得數(shù)據(jù)的行政級(jí)別

dt {str} -- city||province 中心地行政級(jí)別

name {str} -- example:'溫州市||浙江省' 作為中心地的地名

migrationType {str} -- in||out

date {str} -- example:20200202

isExcel {bool} -- true轉(zhuǎn)出為excel格式

"""

r = requests.get(url=UrlFormat(rankMethod,dt,name,migrationType,date))

text = r.text

rawData=json.loads(JsonTextConvert(text))

data= rawData['data']

list = data['list']

nameKey = ''

if rankMethod=='province':

nameKey = 'province_name'

else:

nameKey = 'city_name'

if isExcel == True:

#輸出excel格式數(shù)據(jù)

workbook = xlwt.Workbook(encoding='utf-8') #創(chuàng)建workbook 對(duì)象

worksheet = workbook.add_sheet('sheet1',cell_overwrite_ok=True) #創(chuàng)建工作表sheet

table_head = [nameKey,'value']#表頭

index = 1

for i in range(len(table_head)):

worksheet.write(0,i,table_head[i])

for l in list:

worksheet.write(index,0,l[nameKey])

worksheet.write(index,1,l['value'])

index=index+1

filename = name+date+'.xls'

workbook.save('migration/'+filename) #保存表

else:

#打印數(shù)據(jù)

for l in list:

print(l[nameKey],':',l['value'])

def main():

#第一個(gè)參數(shù)填‘city‘或’province’,為獲取數(shù)據(jù)的行政級(jí)別,分別為市級(jí)或省級(jí)

#第二個(gè)參數(shù)填‘city‘或’province’,為中心地的行政級(jí)別

#第三個(gè)參數(shù)填‘中心地名’,例如‘浙江省’或‘杭州市’

#第四個(gè)參數(shù)填時(shí)間,例如‘20200210’,默認(rèn)每天的零點(diǎn)

#第四個(gè)參數(shù)填True或False,True則輸出Excel(文件路徑注意),否則打印出來

GetData('city','province','浙江省','in','20200210',True)

if __name__ == '__main__':

main()

總結(jié)

以上是生活随笔為你收集整理的python爬取百度迁徙_Python爬虫抓取百度慧眼迁徙大数据(一)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。