request庫 【Python】【親測好用】安裝第三方包報錯:AttributeError:'module' object has no attribute 'main'
阿新 • • 發佈:2019-01-06
0x00 環境簡介和安裝
我這裡使用的是python2.7版本,直接使用pycharm2018這款IDE。
首先在pycharm中配置一下virtualenv環境,virtualenv是一個建立獨立Python執行環境的工具,為一個應用建立一套“隔離”的Python執行環境。
建立new project時選擇建立新的環境,修改你們自己的目錄,如果主機內有多個版本的python直譯器可自行選擇
建立完成後可以在專案中安裝requests庫,file-settings開啟如下介面
單擊右上角綠色加號,搜尋requests並install
這裡如果你的pip版本大於等於10,安裝的時候會報錯,原因是由於新版pip的函式發生了變化,解決辦法參考這個帖子
【Python】【親測好用】安裝第三方包報錯:AttributeError:'module' object has no attribute 'main'
0x01 使用requests
請求方法
-
- GET: 檢視資源
- POST: 增加資源
- PUT: 修改資源
- DELETE: 刪除資源
- HEAD: 檢視響應頭
- OPTIONS: 檢視可用請求方法
基本用法:requests.[methon](url)
import requests response = requests.get('https://www.cnblogs.com/Ragd0ll/p/10176258.html') print(response.status_code) # 列印狀態碼 print(response.url) #列印請求url print(response.headers) # 列印頭資訊 print(response.cookies) # 列印cookie資訊 print(response.text) #以文字形式列印網頁原始碼 print(response.content) #以位元組流形式列印
帶引數的get請求:
第一種直接將引數放在url內
import requests response = requests.get(http://httpbin.org/get?name=gemey&age=22) print(response.text)
第二種是將引數放入字典,然後在請求時給params引數賦值
import requests data = { 'name': 'tom', 'age': 20 } response = requests.get('http://httpbin.org/get', params=data) print(response.text)
兩段程式碼的結果相同
基本POST請求:
import requests data = {'name':'tom','age':'22'} response = requests.post('http://httpbin.org/post', data=data)
簡單儲存一個二進位制檔案
import requests response = requests.get('https://img2018.cnblogs.com/blog/1342178/201812/1342178-20181225201042109-1353349536.png') b = response.content with open('F://fengjing.jpg','wb') as f: f.write(b)
為你的請求新增頭資訊
import requests heads = {} heads['User-Agent'] = 'Mozilla/5.0 ' \ '(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \ '(KHTML, like Gecko) Version/5.1 Safari/534.50' response = requests.get('https://home.cnblogs.com/u/Ragd0ll/',headers=headers)
獲取cookie
import requests response = requests.get('https://home.cnblogs.com/u/Ragd0ll/') print(response.cookies) print(type(response.cookies)) for k,v in response.cookies.items(): print(k+':'+v)
會話維持
import requests session = requests.Session() session.get('http://httpbin.org/cookies/set/number/12345') response = session.get('http://httpbin.org/cookies') print(response.text)
證書驗證設定
import requests from requests.packages import urllib3 urllib3.disable_warnings() #從urllib3中消除警告 response = requests.get('https://www.12306.cn',verify=False) #證書驗證設為FALSE print(response.status_code)
超時異常捕獲
import requests from requests.exceptions import ReadTimeout try: res = requests.get('http://httpbin.org', timeout=0.1) print(res.status_code) except ReadTimeout: print(timeout)
異常處理
import requests from requests.exceptions import ReadTimeout,HTTPError,RequestException try: response = requests.get('http://www.baidu.com',timeout=0.5) print(response.status_code) except ReadTimeout: print('timeout') except HTTPError: print('httperror') except RequestException: print('reqerror')