如何在python上发布表单请求

时间:2019-08-22 17:27:19

标签: python python-requests

我正在尝试填写that之类的表格并自动提交。为此,我在登录时嗅探了数据包。

POST /?pg=ogrgiris HTTP/1.1
Host: xxx.xxx.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Origin: http://xxx.xxx.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15
Referer: http://xxx.xxx.com/?pg=ogrgiris
Upgrade-Insecure-Requests: 1
DNT: 1
Content-Length: 60
Connection: close

seviye=700&ilkodu=34&kurumkodu=317381&ogrencino=40&isim=ahm

我在打suite套件中重复了那个小包,发现工作正常。响应是成员页面的html。

现在,我尝试在python上执行此操作。代码如下:

 import requests
 url = 'http://xxx.xxx.com/?pg=ogrgiris'
 headers = {'Host':'xxx.xxx.com',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate',
'Content-Type':'application/x-www-form-urlencoded',
'Referer':'http://xxx.xxx.com/?pg=ogrgiris',
'Content-Lenght':'60','Connection':'close'}

credentials = {'seviye': '700','ilkodu': '34','kurumkodu': '317381','ogrecino': '40','isim': 'ahm'}


r = requests.post(url,headers=headers, data=credentials)
print(r.content)

问题是,即使我发送了所有credentials足以登录的代码,代码也会打印登录页面的html。如何获取成员页面?谢谢。

2 个答案:

答案 0 :(得分:0)

如果您的目标是复制样本请求,那么您会丢失很多标头; Content-Type: application/x-www-form-urlencoded尤其重要,因为它将告诉HTTP客户端如何格式化/编码有效负载。

查看requests的文档,以了解这些表单帖子如何工作。

答案 1 :(得分:0)

如果POST请求显示包含所需内容的页面,则问题仅在于您以JSON形式发送数据,而不是以“ form”数据格式(application/x-www-form-urlencoded)发送。

如果在请求基础上创建了会话,而您又需要对所请求的数据进行另一个请求,那么您就必须处理cookie。

数据格式问题:

r = requests.post(url, headers=headers, data=credentials)

Kwarg json =按照以下方式创建请求正文:

{"ogrecino": "40", "ilkodu": "34", "isim": "ahm", "kurumkodu": "317381", "seviye": "700"}

data=创建如下请求正文:

seviye=700&ilkodu=34&kurumkodu=317381&ogrencino=40&isim=ahm

您可以尝试https://httpbin.org

from requests import post


msg = {"a": 1, "b": True}
print(post("https://httpbin.org/post", data=msg).json())  # Data as Form data, look at key `form`, it's object in JSON because it's Form data format
print(post("https://httpbin.org/post", json=msg).json())  # Data as json, look at key `data`, it's string