#介紹:使用requests能夠模擬瀏覽器的請求,比起以前用到的urllib,requests模塊的api更加便捷(本質就是封裝了urllib3) #注意:requests庫發送請求將網頁內容下載下來之後,並不會執行js代碼,這須要咱們本身分析目標站點而後發起新的request請求 #安裝:pip3 install requests #各類請求方式:經常使用的就是requests.get()和requests.post() >>> import requests >>> r = requests.get('https://api.github.com/events') >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'}) >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'}) >>> r = requests.delete('http://httpbin.org/delete') >>> r = requests.head('http://httpbin.org/get') >>> r = requests.options('http://httpbin.org/get') #建議在正式學習requests前,先熟悉下HTTP協議 http://www.cnblogs.com/linhaifeng/p/6266327.html
1.基本請求html
import requests response=requests.get('http://dig.chouti.com/') print(response.text)
二、帶參數的GET請求->paramspython
#在請求頭內將本身假裝成瀏覽器,不然百度不會正常返回頁面內容 import requests response=requests.get('https://www.baidu.com/s?wd=python&pn=1', headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36', }) print(response.text) #若是查詢關鍵詞是中文或者有其餘特殊符號,則不得不進行url編碼 from urllib.parse import urlencode wd='egon老師' encode_res=urlencode({'k':wd},encoding='utf-8') keyword=encode_res.split('=')[1] print(keyword) # 而後拼接成url url='https://www.baidu.com/s?wd=%s&pn=1' %keyword response=requests.get(url, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36', }) res1=response.text 本身拼接GET參數
#上述操做能夠用requests模塊的一個params參數搞定,本質仍是調用urlencode from urllib.parse import urlencode wd='egon老師' pn=1 response=requests.get('https://www.baidu.com/s', params={ 'wd':wd, 'pn':pn }, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36', }) res2=response.text #驗證結果,打開a.html與b.html頁面內容同樣 with open('a.html','w',encoding='utf-8') as f: f.write(res1) with open('b.html', 'w', encoding='utf-8') as f: f.write(res2) params參數的使用
三、帶參數的GET請求->headersgit
#一般咱們在發送請求時都須要帶上請求頭,請求頭是將自身假裝成瀏覽器的關鍵,常見的有用的請求頭以下 Host Referer #大型網站一般都會根據該參數判斷請求的來源 User-Agent #客戶端 Cookie #Cookie信息雖然包含在請求頭裏,但requests模塊有單獨的參數來處理他,headers={}內就不要放它了
#添加headers(瀏覽器會識別請求頭,不加可能會被拒絕訪問,好比訪問https://www.zhihu.com/explore) import requests response=requests.get('https://www.zhihu.com/explore') response.status_code #500 #本身定製headers headers={ 'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36', } respone=requests.get('https://www.zhihu.com/explore', headers=headers) print(respone.status_code) #200
四、帶參數的GET請求->cookiesgithub
#登陸github,而後從瀏覽器中獲取cookies,之後就能夠直接拿着cookie登陸了,無需輸入用戶名密碼 #用戶名:egonlin 郵箱378533872@qq.com 密碼lhf@123 import requests Cookies={ 'user_session':'wGMHFJKgDcmRIVvcA14_Wrt_3xaUyJNsBnPbYzEL6L0bHcfc', } response=requests.get('https://github.com/settings/emails', cookies=Cookies) #github對請求頭沒有什麼限制,咱們無需定製user-agent,對於其餘網站可能還須要定製 print('378533872@qq.com' in response.text) #True
1.介紹正則表達式
#GET請求 HTTP默認的請求方法就是GET * 沒有請求體 * 數據必須在1K以內! * GET請求數據會暴露在瀏覽器的地址欄中 GET請求經常使用的操做: 1. 在瀏覽器的地址欄中直接給出URL,那麼就必定是GET請求 2. 點擊頁面上的超連接也必定是GET請求 3. 提交表單時,表單默認使用GET請求,但能夠設置爲POST #POST請求 (1). 數據不會出如今地址欄中 (2). 數據的大小沒有上限 (3). 有請求體 (4). 請求體中若是存在中文,會使用URL編碼! #!!!requests.post()用法與requests.get()徹底一致,特殊的是requests.post()有一個data參數,用來存放請求體數據
二、發送post請求,模擬瀏覽器的登陸行爲json
注:對於登陸來講,應該輸錯用戶名或密碼而後分析抓包流程,用腦子想想,輸對了瀏覽器就跳轉了,還分析個毛線,累死你也找不到包
''' 一 目標站點分析 瀏覽器輸入https://github.com/login 而後輸入錯誤的帳號密碼,抓包 發現登陸行爲是post提交到:https://github.com/session 並且請求頭包含cookie 並且請求體包含: commit:Sign in utf8:✓ authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ== login:egonlin password:123 二 流程分析 先GET:https://github.com/login拿到初始cookie與authenticity_token 返回POST:https://github.com/session, 帶上初始cookie,帶上請求體(authenticity_token,用戶名,密碼等) 最後拿到登陸cookie ps:若是密碼時密文形式,則能夠先輸錯帳號,輸對密碼,而後到瀏覽器中拿到加密後的密碼,github的密碼是明文 ''' import requests import re #第一次請求 r1=requests.get('https://github.com/login') r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被受權) authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #從頁面中拿到CSRF TOKEN #第二次請求:帶着初始cookie和TOKEN發送POST請求給登陸頁面,帶上帳號密碼 data={ 'commit':'Sign in', 'utf8':'✓', 'authenticity_token':authenticity_token, 'login':'317828332@qq.com', 'password':'alex3714' } r2=requests.post('https://github.com/session', data=data, cookies=r1_cookie ) login_cookie=r2.cookies.get_dict() #第三次請求:之後的登陸,拿着login_cookie就能夠,好比訪問一些我的配置 r3=requests.get('https://github.com/settings/emails', cookies=login_cookie) print('317828332@qq.com' in r3.text) #True 自動登陸github(本身處理cookie信息)
import requests import re session=requests.session() #第一次請求 r1=session.get('https://github.com/login') authenticity_token=re.findall(r'name="authenticity_token".*?value="(.*?)"',r1.text)[0] #從頁面中拿到CSRF TOKEN #第二次請求 data={ 'commit':'Sign in', 'utf8':'✓', 'authenticity_token':authenticity_token, 'login':'317828332@qq.com', 'password':'alex3714' } r2=session.post('https://github.com/session', data=data, ) #第三次請求 r3=session.get('https://github.com/settings/emails') print('317828332@qq.com' in r3.text) #True requests.session()自動幫咱們保存cookie信息
注意:api
re.compile() 能夠把正則表達式編譯成一個正則表達式對象.瀏覽器
re.findall() 方法讀取html 中包含 imgre(正則表達式)的數據。cookie
r.text和r.content的區別是什麼呢?session
r.text是unicode編碼的響應內容(r.text is the content of the response in unicode),
r.content是字符編碼的響應內容(r.content is the content of the response in bytes);
text屬性會嘗試按照encoding屬性自動將響應的內容進行轉碼後返回,若是encoding爲None,requests會按照chardet(這是什麼?)猜想正確的編碼;若是你想取文本,能夠經過r.text, 若是想取圖片,文件,則能夠經過r.content(這點我如今也不是很明白).針對響應內容是二進制文件(如圖片)的場景,content屬性獲取響應的原始內容(以字節爲單位)
示例:登陸github
import requests import re #第一次請求 # GET請求 # 請求頭 # - 獲取token和 # - User-agent # - cookie # 第二次請求 #POST請求 #請求頭 # referer # User-agent #請求體 #獲取data # 第三次請求,登陸成功以後 #- 請求以前本身先登陸一下,看一下有沒有referer #- 請求新的url,進行其餘操做 #- 查看用戶名在不在裏面 #第一次請求 response1 = requests.get( "https://github.com/login", headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36", }, ) authenticity_token = re.findall('name="authenticity_token".*?value="(.*?)"',response1.text,re.S) r1_cookies = response1.cookies.get_dict() # print(r1_cookies,"cookie") #獲取到的cookie #第二次請求 response2 = requests.post( "https://github.com/session", headers = { "Referer": "https://github.com/", "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36", }, data={ "commit":"Sign in", "utf8":"✓", "authenticity_token":authenticity_token, "login":"oridn", "password":"xxxx", zhy..azjash1234 }, cookies = r1_cookies ) print(response2.status_code) print(response2.history) #跳轉的歷史狀態碼 #第三次請求,登陸成功以後,訪問其餘頁面 r2_cookies = response2.cookies.get_dict() #拿上cookie,知道是你登陸了,就開始訪問頁面 response3 = requests.get( "https://github.com/settings/emails", headers = { "Referer": "https://github.com/", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36", }, cookies = r2_cookies, ) print(response3.text) print("oridn" in response3.text) #True返回True說明就成功了
3.補充
requests.post(url='xxxxxxxx', data={'xxx':'yyy'}) #沒有指定請求頭,#默認的請求頭:application/x-www-form-urlencoed #若是咱們自定義請求頭是application/json,而且用data傳值, 則服務端取不到值 requests.post(url='', data={'':1,}, headers={ 'content-type':'application/json' }) requests.post(url='', json={'':1,}, ) #默認的請求頭:application/json