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