python网络爬虫之requests模块
什么是requests模塊
requests模塊是python中原生的基于網(wǎng)絡(luò)請(qǐng)求的模塊,其主要作用是用來(lái)模擬瀏覽器發(fā)起請(qǐng)求。功能強(qiáng)大,用法簡(jiǎn)潔高效。在爬蟲(chóng)領(lǐng)域中占據(jù)著半壁江山的地位。
因?yàn)樵谑褂胾rllib模塊的時(shí)候,會(huì)有諸多不便之處,總結(jié)如下:手動(dòng)處理url編碼手動(dòng)處理post請(qǐng)求參數(shù)處理cookie和代理操作繁瑣......使用requests模塊:自動(dòng)處理url編碼自動(dòng)處理post請(qǐng)求參數(shù)簡(jiǎn)化cookie和代理操作...... 為什么要使用requests模塊如何使用requests模塊
- 安裝:
- pip install requests
- 使用流程
- 指定url
- 基于requests模塊發(fā)起請(qǐng)求
- 獲取響應(yīng)對(duì)象中的數(shù)據(jù)值
- 持久化存儲(chǔ)
基于如下5點(diǎn)展開(kāi)requests模塊的練習(xí)
1.基于requests模塊的get請(qǐng)求 2.基于requests模塊的post請(qǐng)求 3.基于requests模塊ajax的get請(qǐng)求 4.基于requests模塊ajax的post請(qǐng)求 5.綜合練習(xí)案例演示代碼演示:
1.基于requests模塊的get請(qǐng)求,需求:
import requests#1.指定url headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' } url = 'https://www.sogou.com/' #2.發(fā)起請(qǐng)求:get返回一個(gè)響應(yīng)對(duì)象 response = requests.get(url=url,verify=False,headers=headers) #3.獲取響應(yīng)數(shù)據(jù):text屬性返回的是字符串形式的響應(yīng)數(shù)據(jù) page_text = response.text print(page_text) #4.持久化存儲(chǔ) with open('./sogou.html','w',encoding='utf-8') as fp:fp.write(page_text)print('over!!!') 需求:爬取搜狗首頁(yè)的頁(yè)面數(shù)據(jù) import requests wd = input('enter a word:') #url攜帶的參數(shù)需要手動(dòng)處理 url = 'https://www.sogou.com/web'#將參數(shù)手動(dòng)處理成了字典的形式 param = {'query':wd } #使用params參數(shù)處理了請(qǐng)求攜帶的參數(shù) response = requests.get(url=url,params=param)page_text = response.text fileName = wd+'.html' #文件名#數(shù)據(jù)持久化 with open(fileName,'w',encoding='utf-8') as fp:fp.write(page_text)print(fileName,'爬取成功!') 需求:爬取指定詞條對(duì)應(yīng)搜狗搜索結(jié)果頁(yè)面?
2.基于requests模塊的post請(qǐng)求:
import requests url = 'https://fanyi.baidu.com/sug' wd = input('enter something of English:') #這里輸入英文翻譯成中文 #url攜帶參數(shù)的封裝 data = {'kw':wd } #發(fā)起一個(gè)post請(qǐng)求 #UA檢測(cè)這種反爬機(jī)制被應(yīng)用在了大部分的網(wǎng)站中 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' } response = requests.post(url=url,data=data,headers=headers) #獲取響應(yīng)數(shù)據(jù) #response.text #獲取的是字符串形式的json數(shù)據(jù) obj_json = response.json() #json()返回的就是對(duì)象類型的響應(yīng)數(shù)據(jù) print(obj_json) 需求:破解百度翻譯?
?如果是Content-Type:application/json,可以obj_json = response.json() #json()返回的就是對(duì)象類型的響應(yīng)數(shù)據(jù)
?
?
3.基于requests模塊ajax的git請(qǐng)求:
?
prsponse這里的數(shù)據(jù)在世我們拿到的數(shù)據(jù)信息
在線JSON校驗(yàn)格式化工具:http://www.bejson.com/
?
#!/usr/bin/env python # -*- coding:utf-8 -*-import requests import urllib.request if __name__ == "__main__":#指定ajax-get請(qǐng)求的url(通過(guò)抓包進(jìn)行獲取)url = 'https://movie.douban.com/j/chart/top_list?'#定制請(qǐng)求頭信息,相關(guān)的頭信息必須封裝在字典結(jié)構(gòu)中headers = {#定制請(qǐng)求頭中的User-Agent參數(shù),當(dāng)然也可以定制請(qǐng)求頭中其他的參數(shù)'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',}#定制get請(qǐng)求攜帶的參數(shù)(從抓包工具中獲取)param = {'type':'5','interval_id':'100:90','action':'','start':'0','limit':'20'}#發(fā)起get請(qǐng)求,獲取響應(yīng)對(duì)象response = requests.get(url=url,headers=headers,params=param)#獲取響應(yīng)內(nèi)容:響應(yīng)內(nèi)容為json串print(response.text)movie_list = response.json()print(movie_list) #y以json格式拿取列表里嵌套著字典,每個(gè)字典是一電影的詳情 all_names = []for dic in movie_list:print(dic)name = dic['title']all_names.append(name)print(all_names)需求:爬取豆瓣電影分類排行榜的電影名稱 需求:爬取豆瓣電影分類的電影名稱?
?4.基于requests模塊ajax的post請(qǐng)求:
ajax動(dòng)態(tài)加載數(shù)據(jù)抓包查看方法
?
?
?
#!/usr/bin/env python # -*- coding:utf-8 -*-import requests import urllib.requestif __name__ == "__main__":#指定ajax-post請(qǐng)求的url(通過(guò)抓包進(jìn)行獲取)url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'#定制請(qǐng)求頭信息,相關(guān)的頭信息必須封裝在字典結(jié)構(gòu)中headers = {#定制請(qǐng)求頭中的User-Agent參數(shù),當(dāng)然也可以定制請(qǐng)求頭中其他的參數(shù)'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',}#定制post請(qǐng)求攜帶的參數(shù)(從抓包工具中獲取)data = {'cname':'','pid':'','keyword':'北京','pageIndex': '1','pageSize': '100'}#發(fā)起post請(qǐng)求,獲取響應(yīng)對(duì)象response = requests.post(url=url,headers=headers,data=data)#獲取響應(yīng)內(nèi)容:響應(yīng)內(nèi)容為json串print(response.text) 需求:爬取肯德基餐廳查詢http://www.kfc.com.cn/kfccda/index.aspx中指定地點(diǎn)的餐廳數(shù)據(jù)?
5.綜合練習(xí):
?這里引入一個(gè)fake_useragent第三方庫(kù),隨機(jī)生成UserAgent請(qǐng)求頭設(shè)置
安裝 :pip3 install fake-useragent 查看安裝的版本號(hào):pip3 list 使用: from fake_useragent import UserAgentua = UserAgent() # 禁用服務(wù)器緩存:ua = UserAgent(use_cache_server=False), 不緩存數(shù)據(jù):ua = UserAgent(cache=False),忽略ssl驗(yàn)證:ua = UserAgent(verify_ssl=False) print(ua.ie) #隨機(jī)打印ie瀏覽器任意版本 print(ua.firefox) #隨機(jī)打印firefox瀏覽器任意版本 print(ua.chrome) #隨機(jī)打印chrome瀏覽器任意版本 print(ua.random) #隨機(jī)打印任意廠家的瀏覽器?
需求: 爬取國(guó)家藥品監(jiān)督管理局企業(yè)許可相關(guān)信息:http://125.35.6.84:81/xk/問(wèn)題描述:獲取分頁(yè)數(shù)據(jù),根據(jù)不同企業(yè),在二級(jí)頁(yè)面獲取許可相關(guān)信息知識(shí)點(diǎn): 1.抓取數(shù)據(jù)包使用ajax的post請(qǐng)求 2.使用fake_useragent實(shí)現(xiàn)動(dòng)態(tài)生成UA 3.該請(qǐng)求響應(yīng)回來(lái)的數(shù)據(jù)有兩個(gè),可以根據(jù)content-type,來(lái)獲取指定的響應(yīng)數(shù)據(jù):一個(gè)是基于text一個(gè)是基于json的4.json在線格式化效驗(yàn)工具:http://www.bejson.com/
1.抓取ajax數(shù)據(jù)包
post提交的分頁(yè)請(qǐng)求數(shù)據(jù)
通過(guò)抓包工具獲得首頁(yè)li標(biāo)簽公司每條信息,從中提取二級(jí)頁(yè)面跳轉(zhuǎn)地址
獲取二級(jí)頁(yè)面信息:
Response才是我們程序獲取的數(shù)據(jù)
import requests from fake_useragent import UserAgentua = UserAgent(use_cache_server=False).random headers = {'User-Agent':ua }url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsList' for page in range(3,5):data = {'on': 'true','page': str(page),'pageSize': '15','productName':'','conditionType': '1','applyname':'','applysn':''}json_text = requests.post(url=url,data=data,headers=headers).json()all_id_list = []for dict in json_text['list']:id = dict['ID']#用于二級(jí)頁(yè)面數(shù)據(jù)獲取#下列詳情信息可以在二級(jí)頁(yè)面中獲取# name = dict['EPS_NAME']# product = dict['PRODUCT_SN']# man_name = dict['QF_MANAGER_NAME']# d1 = dict['XC_DATE']# d2 = dict['XK_DATE'] all_id_list.append(id)#該url是一個(gè)ajax的post請(qǐng)求post_url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById'for id in all_id_list:post_data = {'id':id}response = requests.post(url=post_url,data=post_data,headers=headers)#該請(qǐng)求響應(yīng)回來(lái)的數(shù)據(jù)有兩個(gè),一個(gè)是基于text,一個(gè)是基于json的,所以可以根據(jù)content-type,來(lái)獲取指定的響應(yīng)數(shù)據(jù)if response.headers['Content-Type'] == 'application/json;charset=UTF-8':#print(response.json())#進(jìn)行json解析json_text = response.json()print(json_text['businessPerson'],json_text['productSn'],type(json_text['productSn'])) 代碼展示?
轉(zhuǎn)載于:https://www.cnblogs.com/iamjianghao/p/10832609.html
總結(jié)
以上是生活随笔為你收集整理的python网络爬虫之requests模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 第四次上级作业
- 下一篇: websocket python爬虫_p