python模擬登陸、POST/GET請求方式
python模擬登陸、POST/GET請求
通常我們在訪問網(wǎng)頁時,都會通過某個輸入框輸入數(shù)據(jù),網(wǎng)頁就會發(fā)出POST、GET或者其他形式向服務(wù)器發(fā)起請求,成功后并返回數(shù)據(jù)到前臺展示。以下針對python的requests庫做簡單介紹。
前提先安裝python以及requests庫
安裝requests:
pip install requests
請求測試url = http://www.test.com
一、GET請求
1、無請求參數(shù):直接訪問某url鏈接即可獲取數(shù)據(jù)
result = requests.get(url=url) print(result.status_code) # 請求狀態(tài) print(result.url)# 請求url print(result.text) # 請求結(jié)果
2、有請求參數(shù):鍵值對形式表示參數(shù)
result = requests.get(url=url, params={'keyword1':'val1','keyword2':'val2'})
#或者可以直接先拼接url
#new_url = url + '?keyword1=' + val1 + '&keyword1=' +val2
#result = requests.get(url=new_url)
print(result.status_code) # 請求狀態(tài)
print(result.url)# 請求url
print(result.text) # 請求結(jié)果
3、有請求頭部參數(shù):鍵值對形式表示參數(shù)
result = requests.get(url=url, params={'keyword1':'val1','keyword2':'val2'})
#或者可以直接先拼接url
#new_url = url + '?keyword1=' + val1 + '&keyword1=' +val2
#result = requests.get(url=new_url)
print(result.status_code) # 請求狀態(tài)
print(result.url)# 請求url
print(result.text) # 請求結(jié)果
二、POST請求
1、請求的結(jié)果集是application/x-www-form-urlencoded
result = requests.post(url=url,data={'keyword1':'val1','keyword2':'val2'},headers={'Content-Type':'application/x-www-form-urlencoded'})
print(result.status_code) # 請求狀態(tài)
print(result.url)# 請求url
print(result.text) # 請求結(jié)果
2、請求的結(jié)果集是multipart/form-data
result = requests.post(url=url,data={'keyword1':'val1','keyword2':'val2'},headers={'Content-Type':'multipart/form-data'})
print(result.status_code) # 請求狀態(tài)
print(result.url)# 請求url
print(result.text) # 請求結(jié)果
3、請求的結(jié)果集是application/json
import json
data = {'keyword1':'val1','keyword2':'val2'}
json_data = json.dumps(data)
result = requests.post(url=url,data=json_data,headers={'Content-Type':'application/json'})
print(result.status_code) # 請求狀態(tài)
print(result.url)# 請求url
print(result.text) # 請求結(jié)果
如下圖:

下來來說一下之前自己遇到的坑,請求方式為POST,且為Request Payload形式的請求。
一開始自以為跟form-data一樣,只傳一個url跟data,且data沒有格式化成JSON,導(dǎo)致請求回來的狀態(tài)為415:服務(wù)器無法處理請求附帶的媒體格式,經(jīng)查閱后來改個格式以及請求頭就順利返回數(shù)據(jù)。
完整demo如下:
import json
import requests
import datetime
import re, urllib.request, lxml.html, http.cookiejar
url = 'http://test.com/products'
# payloadData數(shù)據(jù)
payload_data = {'keyword1': "val1", 'keyword2': "val2"}
# 請求頭設(shè)置
payload_header = {
'Host': 'test.com',
'Content-Type': 'application/json; charset=UTF-8',
}
# 下載超時
timeout = 30
# 代理IP
# proxy_list = {"HTTP":'http://210.22.5.117"3128',"HTTP":'http://163.172.189.32:8811',"HTTP":'http://180.153.144.138:8800'}
json_data = json.dumps(payload_data)
# allow_redirects 是否重定向
# result = requests.post(url=url, data=json_data, headers=payloadHeader, timeout=timeout, proxies=proxy_list, allow_redirects=True)
result = requests.post(url, data=json_data, headers=payload_header, timeout=timeout, allow_redirects=True)
# 下面這種直接填充json參數(shù)的方式也OK
# result = requests.post(url, json=json_data, headers=payload_header)
print("請求耗時:{0}, 狀態(tài)碼:{1}, 結(jié)果:{2}".format(datetime.datetime.now(),res.status_code,res.text))
三、需要模擬登陸后再發(fā)送Post請求
有時候就想模擬頁面上的某些細微的操作,例如登錄后需要在前端利用ajax請求修改數(shù)據(jù)。
如果只是極個別數(shù)量修改的話,那還是前端直接操作快一點。
如果是大批量的修改那還是得借住程序遍歷修改即可。
登錄頁面:

先打開F12進入開發(fā)者模式,然后隨便在上面的表單輸入框數(shù)據(jù),點擊登錄,雖然是錯誤的登錄數(shù)據(jù),我們只是為了查看登錄請求提交的數(shù)據(jù)格式,如下圖:

其中的某些不是我們輸入的隱藏值,我們需要到頁面源碼中的表單獲取,右鍵查看頁面源碼,把那些非自己輸入的 “__VIEWSTATE",”__VIEWSTATEGENERATOR","__EVENTVALIDATION" 的值到原頁面中查找,例如:

也就是說我們得事先先訪問該頁面頁面源碼并解析獲取以上屬性值:
import requests, string
import re, urllib.request, lxml.html, http.cookiejar
login_url = "http://test.com/Login.aspx"
response = urllib.request.urlopen(login_url)
f = response.read()
doc = lxml.html.document_fromstring(f)
VIEWSTATE = doc.xpath("http://input[@id='__VIEWSTATE']/@value")
VIEWSTATEGENERATOR = doc.xpath("http://input[@id='__VIEWSTATEGENERATOR']/@value")
EVENTVALIDATION = doc.xpath("http://input[@id='__EVENTVALIDATION']/@value")
獲取到這些之后,得把這些值放回到Form-Data(表單數(shù)據(jù)中):
from urllib.parse import quote
login_data = urllib.parse.urlencode({
'__EVENTTARGET' : '',
'__EVENTARGUMENT' : '',
'__VIEWSTATE' : VIEWSTATE[0],
'__VIEWSTATEGENERATOR' : VIEWSTATEGENERATOR[0],
'__EVENTVALIDATION' : EVENTVALIDATION[0],
'TextCustomerID' : "真實商戶號",
'TextAdminName' : '真實用戶名',
'TextPassword' : '真實密碼',
'btnLogin.x' : 40,
'btnLogin.y' : 10
}).encode('utf-8')
登錄參數(shù)的編碼很重要,如果沒有進行utf-8編碼會報以下錯誤:
Traceback (most recent call last):
File "c:\users\user\appdata\local\programs\python\python38\lib\http\client.py", line 965, in send
self.sock.sendall(data)
File "c:\users\user\appdata\local\programs\python\python38\lib\ssl.py", line 1201, in sendall
with memoryview(data) as view, view.cast("B") as byte_view:
TypeError: memoryview: a bytes-like object is required, not 'str'
表單數(shù)據(jù)有了,接下來就是把請求頭也要獲取出來:

header = {
'Host': 'www.test.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/x-www-form-urlencoded',
'Origin': 'http://www.test.com',
'Connection': 'keep-alive',
'Referer': 'http://www.test.com/Login.aspx',
'Upgrade-Insecure-Requests': 1
}
模擬登陸并保存cookie:
#模擬登錄請求 login_request = urllib.request.Request(login_url, login_data, Headers) #創(chuàng)建cookie,利用cookie實現(xiàn)持久化登錄 cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) login_result = opener.open(login_request)
最后模擬登陸后,如果是要采集某頁面數(shù)據(jù)的話也可以通過urllib.request.urlopen訪問頁面鏈接讀取頁面源碼進行數(shù)據(jù)采集。
如果有批量數(shù)據(jù)需要進行Post/Get處理,那么就可以把待處理的數(shù)據(jù)獲取好,然后遍歷發(fā)起Post或Get請求即可:
import time, random
var datas = {.....}
for data in datas:
response = requests.get(url, headers = headers, data=json_data, cookies = cj)
# 或
response = requests.post(url, headers = headers, data=json_data, cookies = cj)
time.sleep(random.randint(3, 5))
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pytest參數(shù)化:@pytest.mark.parametrize詳解
pytest.mark.parametrize裝飾器能夠?qū)y試函數(shù)進行參數(shù)化處理,使得一個測試函數(shù)可以用多組數(shù)據(jù)執(zhí)行多次,這有助于檢查不同輸入下的期望輸出是否匹配,提高測試的效率和覆蓋率,裝飾器可以應(yīng)用于函數(shù)、模塊或類,支持多個裝飾器組合使用,增強測試的靈活性和綜合性2024-10-10
Python命令行參數(shù)解析之a(chǎn)rgparse模塊詳解
這篇文章主要介紹了Python命令行參數(shù)解析之a(chǎn)rgparse模塊詳解,argparse?是?Python?的一個標準庫,用于命令行參數(shù)的解析,這意味著我們無需在代碼中手動為變量賦值,而是可以直接在命令行中向程序傳遞相應(yīng)的參數(shù),再由變量去讀取這些參數(shù),需要的朋友可以參考下2023-08-08
python算法測試結(jié)果自動保存到excel表格的實現(xiàn)步驟
我們在進行算法評估是通常會針對每個樣本的算法處理結(jié)果進行統(tǒng)計,例如每個樣本正確預(yù)測數(shù)量、漏檢數(shù)量和誤檢數(shù)量、精度等,本文小編將給大家介紹python算法測試結(jié)果自動保存到excel表格的實現(xiàn)步驟,感興趣的朋友可以參考下2023-12-12
python使用pygame實現(xiàn)笑臉乒乓球彈珠球游戲
這篇文章主要為大家詳細介紹了python使用pygame實現(xiàn)笑臉乒乓球彈珠球游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11

