不知道初入門(mén)python爬蟲(chóng)的朋友是否有過(guò)跟我一樣的經(jīng)歷,書(shū)是早幾年的,書(shū)上的示例代碼可能已經(jīng)不適用了,需要做一些調(diào)整,才能將程序跑通。本人在學(xué)習(xí)python前三章的內(nèi)容,就沒(méi)少碰到這樣的尷尬事,為此耗費(fèi)了較多精力搜索、查閱相關(guān)資料。
前三章主要講如何通過(guò)python的requests庫(kù)使用get/post方法爬取網(wǎng)頁(yè)或者API數(shù)據(jù)。本文說(shuō)說(shuō)我在這方面踩的坑。
1)安裝requests庫(kù)
書(shū)上的建議在pycharm中安裝requests庫(kù),即打卡pycharm,單擊“file”(文件菜單),選擇“default settings”(默認(rèn)設(shè)置)命令,如下圖
選擇“project interpreter”(項(xiàng)目編輯器)命令,確認(rèn)當(dāng)前選擇的編譯器,然后單擊右上角的加號(hào),如下圖
在搜索框輸入:requests(注意,一定要輸入完整,不然容易出錯(cuò)),勾選“Install to user's site packages directory”(安裝到用戶(hù)的站點(diǎn)庫(kù)目錄)選項(xiàng),如果不勾選該選項(xiàng)則會(huì)安裝在臨時(shí)目錄中,然后單擊左下角的“Install Package”(安裝庫(kù))按鈕,如下圖
到這一步就悲劇了,跟書(shū)上展示的完全不一樣,此路不通。而書(shū)中的下一步應(yīng)該如下圖一般
本人從網(wǎng)上查閱了很多資料,至今都無(wú)法修復(fù)圖3中“nothing to show”的情況,如果你有相應(yīng)的解決辦法,歡迎一起討論哦。
2)get/post方法調(diào)用
I、get方法獲取數(shù)據(jù)
書(shū)上只簡(jiǎn)單的給了一個(gè)示例,示例如下
# 使用GET方式抓取數(shù)據(jù)
import requests# 導(dǎo)入requests包
url ='http://www.cntour.cn/'
strhtml = requests.get(url)# GET方式獲取網(wǎng)頁(yè)數(shù)據(jù)
print(strhtml.text)
注:requests.get(url)只適用于不需要表頭參數(shù)的信息獲取,當(dāng)API接口對(duì)表頭數(shù)據(jù)有要求時(shí),該方法已不使用,如下圖API接口
python3已經(jīng)刪除了urllib2的調(diào)用,若用requests調(diào)用接口,該代碼要更改為
#獲取城市列表
import requests#導(dǎo)入requests包
import json#導(dǎo)入json包
host ='http://weather-ali.juheapi.com'
path ='/weather/citys'
method ='GET'
appcode ='65070e518c474ff68837606434083cfa'
querys ='dtype=json'
bodys = {}
url = host + path +'?' + querys
headers = {'Authorization':'APPCODE ' + appcode}? ? ? ?#設(shè)置http包頭
response = requests.get(url,headers=headers)? ? ? ? #調(diào)用http接口
# print(response)
data = response.text#獲取response文本
# print(data)
data = json.loads(data)? ? ? ?#將str字符串轉(zhuǎn)換成dict字典
del data['resultcode']? ? ? ? ? #通過(guò)del刪除字典的前兩個(gè)元素
del data['reason']
print(data)
for item in data['result']:
? ? ?print(type(item))
? ? print(item)
注:API接口調(diào)用時(shí),必傳表頭信息,表頭信息的設(shè)置和接口的調(diào)用如下兩行代碼所示
headers = {'Authorization':'APPCODE ' + appcode}? ? ? ?#設(shè)置http包頭
response = requests.get(url,headers=headers)? ? ? ? #調(diào)用http接口
II、post方法爬取百度翻譯上的信息
輸入網(wǎng)址“https://fanyi.baidu.com/?aldtype=16047#zh/en/”,按F12進(jìn)入谷歌開(kāi)發(fā)者模式,在待翻譯框中輸入“我愛(ài)中國(guó)”,顯示如下
post方法獲取網(wǎng)站信息,信息的爬取是動(dòng)態(tài)的,代碼中需要包含Request URL、Request Headers、Form Data的信息,三者缺一不可。代碼如下:
# 使用POST抓取數(shù)據(jù)
import requests
import json
def get_translate_date(word =None):
? ? ? url ='https://fanyi.baidu.com/v2transapi'
? ? ? chinese = word
? ? ? form_data =? ? ? ? ? ? ? ? ? ? ? ? {'from':'zh','to':'en','query':chinese,'transtype':'realtime','simple_means_flag':'3','sign':'731618.1034963','token':'595cdd9cc5535f5221b042f98a8dff9e'}
? ? ? request_headers = {'Accept':'*/*','Accept-Encoding':'gzip, deflate, br','Accept-Language':'zh-CN,zh;q=0.9','Connection':'keep-alive', \
'Content-Length':'154','Content-Type':'application/x-www-form-urlencoded; charset=UTF-8','Cookie':'REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BIDUPSID=44BBBD72ED6CC7036FE60E4B97D24B27; PSTM=1494408740; hasSeenTips=1; MCITY=-179%3A; BDUSS=9NU1RzQ3pMc2p0Y1FrNlhCR3N5dDZ6ekl0cXdZUHJKQ3VUN1dtRjgydHRZRUJjQUFBQUFBJCQAAAAAAAAAAAEAAADNlc0beWV6aTA4MDYxNzE3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAG3TGFxt0xhcQW; BAIDUID=5AACF8785E214AF7E5AD9394BE0D9F82:FG=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=1446_21125_28607_28584_26350_28603_20718; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; delPer=0; PSINO=5; locale=zh; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1552198524; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1552198524; to_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; from_lang_often=%5B%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D', \
'Host':'fanyi.baidu.com','Origin':'https://fanyi.baidu.com','Referer':'https://fanyi.baidu.com/?aldtype=16047','User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Mobile Safari/537.36', \
'X-Requested-With':'XMLHttpRequest'}
# 請(qǐng)求表單數(shù)據(jù)
? ? response = requests.post(url,data = form_data,headers = request_headers)
# 將JSON格式字符串轉(zhuǎn)字典
? ? content = json.loads(response.text)
# 打印翻譯后的數(shù)據(jù)
? ? print(content['trans_result']['data'][0]['dst'])
if __name__ =='__main__':
? ? get_translate_date('我愛(ài)中國(guó)')
注:輸入的中文不同,F(xiàn)orm Data中的sign和token會(huì)不同,本人暫未解決該問(wèn)題,期待與大家一起討論批量出入中文時(shí),該如何動(dòng)態(tài)獲取Form Data中的sign和token