如何使用Python mechanize发送负载

3 投票
1 回答
2097 浏览
提问于 2025-04-17 16:39

我想从网上获取一些信息,所以我用Python的mechanize模块来实现这个功能。不过在请求的时候需要发送一些数据,我试了很多方法但还是没成功。请帮帮我。
以下是我抓取到的请求数据:

请求信息

网址:xxxxxx
请求方式:POST
状态码:200 OK

请求头

**Accept:application/json, text/javascript, */*; q=0.01**  
Accept-Charset:gb18030,utf-8;q=0.7,*;q=0.3  
Accept-Encoding:gzip,deflate,sdch  
Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4  
Connection:keep-alive  
Content-Length:52  
**Content-Type:application/json; charset=UTF-8**  
Cookie:ASP.NET_SessionId: sanntewiq5cz5uq1y0l5g3gy  
Host:xxx.xxx.xxx.xxx:8500  
Origin:xxx.xxx.xxx.xxx:8500  
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17  
**X-Requested-With:XMLHttpRequest**

请求数据

{dispatchorderid:"966A48E572624F2FB2E99F371C232729"}

这是我的代码:

br = mechanize.Browser()
payload = {'dispatchorderid': "966A48E572624F2FB2E99F371C232729"}
json_data = json.dumps(payload)
br.addheaders = [('Content-Type', 'application/json; charset=UTF-8'),
                ('Accept', 'application/json, text/javascript, */*; q=0.01'),
                ('X-Requested-With', 'XMLHttpRequest')]
br.set_debug_http(True)
res = br.open(url, json_data)

当我运行这个脚本时,发送的信息是:

发送内容:'POST /DealerManage/AddDispatchorder.aspx/GetDispatchorderEntityList HTTP/1.1\r\nAccept-Encoding: identity\r\nContent-Length: 55
连接:close
接受:application/json, text/javascript, /; q=0.01
主机:125.64.15.71:8500
Cookie: ASP.NET_SessionId=34dyw50d3omel2vbsvm41zwp
X-Requested-With: XMLHttpRequest
*内容类型:application/x-www-form-urlencoded'



为什么内容类型没有变成'application/json; charset=UTF-8'呢?

1 个回答

-1

这个问题虽然很老了,但现在用requests这个包来处理起来简单多了:

import requests
head = { 'Content-Type': 'application/json; charset=UTF-8',
         'Accept': 'application/json, text/javascript, */*; q=0.01',
         'X-Requested-With': 'XMLHttpRequest' }
data = dict(dispatchorderid="966A48E572624F2FB2E99F371C232729")
response = requests.post(url, json.dumps(data), headers=head)

print response.text

撰写回答