【问题标题】:Making LoadControl XHR request in Mechanize在 Mechanize 中发出 LoadControl XHR 请求
【发布时间】:2019-11-17 02:38:23
【问题描述】:

我有一个带有 Mechanize 的 Python 脚本来导航外部网站。该网站显然是用 ASP.NET 编写的,并且正在使用动态控件。我正在尝试模拟 XHR 来加载控件(通常通过单击 <button> 来触发),但是每当我创建 XHR 时 ASP 服务器都会返回 500 错误。我匹配了正常发送的 POST 请求的负载。

基本上,我正在这样做:

browser = mechanize.Browser()

browser.open('https://external.site/page.html')
# Here would be code to parse the content and extract the
# parameters for the XHR.

# Now we're making the XHR to update the control:
body = urllib.parse.urlencode({
    'request': {
                'control': 'Control_Name',
                'parameters': parameters,
            }
        })

request = mechanize.Request(
    url='https://external.site/server.asmx/LoadControl',
    data=body,
    method='POST',
)

response = browser.open(request)

当我这样做时,浏览器会引发异常,因为它从服务器收到 500。

由于 CORS 检查或类似的原因,这可能是不可能的,但我觉得我根本没有提出正确的请求。当我通过浏览器使用外部网站时,URL 和数据负载与通常发送的内容相匹配。

有没有办法通过 Mechanize 发出 LoadControl 请求?

作为参考,我尝试导航的网站上的按钮如下所示:

<button type="button"
     data-focus="{&quot;LoadParams&quot;:{&quot;ControlName&quot;: [lots of key/value pairs here here]"}}"
     data-action="GB.LoadControl">Button</button>

当我单击按钮时,XHR 包含此有效负载:

{
    "request": {
        [the data here matches data-focus from the button]
    }
}

以及请求头:

POST /MyService.asmx/LoadControl HTTP/1.1
Host: myservice.com
Connection: keep-alive
Content-Length: 367
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest 
User-Agent: Mozilla/5.0 (X11; CrOS x86_64 12871.23.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.31 Safari/537.36 
Content-Type: application/json; charset=UTF-8 
Origin: https://myservice.com 
Sec-Fetch-Site: same-origin 
Sec-Fetch-Mode: cors 
Sec-Fetch-Dest: empty 
Referer: https://myservice.comService.aspx?AGU=1&[...] 
Accept-Encoding: gzip, deflate, br 
Accept-Language: en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7 
Cookie: BIGipServerSD_Home=224813834.20480.0000; ASP.NET_SessionId=152i5tiwq1r2cbiuamxxxxxx; PVUE=00

【问题讨论】:

  • XHR 请求是作为application/json 内容类型还是其他内容类型发送的?您能否在您的问题中分享您网络浏览器中“网络”选项卡中的请求信息?
  • @OluwafemiSule 这是application/json。我添加了标题。

标签: python asp.net mechanize


【解决方案1】:

发送到服务器的机械化请求中的Content-type headerapplication/x-www-form-urlencoded

headers参数中设置Content-typeapplication/jsonrequest传入

headers = {'Content-type': 'application/json'}
request = mechanize.Request(
    url='https://external.site/server.asmx/LoadControl',
    data=body,
    method='POST',
    headers=headers
)

【讨论】:

  • 谢谢!这是谜题的第一部分。我还必须更改有效负载 - urllib.parse.urlencode 适用于 application/x-www-form-urlencoded,但由于我选择了 application/json,因此我不得不通过 json.dumps() 运行它。您让我找到了正确的解决方案,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 2014-05-31
  • 2011-06-03
  • 2020-05-14
相关资源
最近更新 更多