【问题标题】:Python request() in 2.x versus 3.x2.x 与 3.x 中的 Python request()
【发布时间】:2019-12-16 14:24:13
【问题描述】:

使用 Python 2.X,以下脚本可以正常运行:

import requests

url = "https://rrcsearch3.neubus.com/esd3-rrc/api.php"

querystring = {"function":"SearchImages"}

payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"json\"\r\n\r\n{\"Neusearch\":{\"profile\":\"15\",\"Searchitems\":{\"item\":[{\"key\":\"district\",\"value\":\"02\"}]},\"includeName\":\"\",\"excludeName\":\"\",\"excludeValue\":\"\",\"recordFromDate\":\"\",\"recordToDate\":\"\",\"page\":0,\"pageSize\":1000000,\"strict\":\"true\",\"saveSearch\":\"true\"}}\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
    'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
    'Accept': "application/json, text/javascript, */*; q=0.01",
    'Accept-Encoding': "gzip, deflate, br",
    'Accept-Language': "en-US,en;q=0.9",
    'api_key': "publicuser",
    'api_sig': "68461babf138014f252e64732ef3b1a0",
    'Connection': "keep-alive",
    'Cookie': "Neups=50; NeuESD=g383thb2ukc5q6klcd33m0t7c0; NeuAuth=d6b27ce8e6454176b9f50d9231e51045,Neups=50; NeuESD=g383thb2ukc5q6klcd33m0t7c0; NeuAuth=d6b27ce8e6454176b9f50d9231e51045; NeuESD=2oehhlibjmt3ur8m7fkvj0qmq6",
    'Host': "rrcsearch3.neubus.com",
    'Origin': "https://rrcsearch3.neubus.com",
    'Referer': "https://rrcsearch3.neubus.com/esd3-rrc/index.php?_module_=esd&_action_=keysearch&profile=15",
    'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
    'X-Requested-With': "XMLHttpRequest",
    'Content-Type': "application/x-www-form-urlencoded",
    'Cache-Control': "no-cache",
    'Postman-Token': "3a7a923e-1a49-4449-8950-db8e8df6ed5d,0f467bb5-860a-4113-88b7-1be0ce89d388",
    'Content-Length': "400",
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)

但是,当使用 Python 3.7 时,完全相同的脚本会产生以下输出:

{"status":"fail","message":"Missing or invalid parameter: 'json'"}

为什么会发生这种情况,我该如何解决?

【问题讨论】:

    标签: python-3.x web-scraping request python-2.x


    【解决方案1】:

    根据docs json 正在将数据传递给正文,尝试将有效负载设置为json 参数:

    response = requests.request("POST", url, json=payload, headers=headers, params=querystring)
    

    【讨论】:

    • 在上面用你的替换我的初始语句后,输出保持不变:{"status":"fail","message":"Missing or invalid parameter: 'json'"}
    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 2019-05-03
    • 2021-01-13
    相关资源
    最近更新 更多