我有一个带有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="{"LoadParams":{"ControlName": [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
发送到服务器的机械化请求中的Content-type
header为Content-type
。
在application/x-www-form-urlencoded
中传递的Content-type
参数中将application/json
设置为headers
request