使用Python Requests模拟Ajax POST调用

5


我正在做一个项目,我的解析器获取特定网站上每个视频的数据并将其保存到我的数据库中。我已经完成了除了视频的完整链接之外的所有内容,该链接是隐藏的。
有一个播放器,在页面加载时自动启动。我已经找到了启动播放器的JavaScript代码:

function getVidData(resolution, init) {
    << some code here >>
    jQuery.ajax({type: 'POST', url: '/ajaxdata.php', dataType: 'json', data: 'mod=videodata&vid=48902&res=' + resolution, success: function (response) {
        if (response.error != '' && response.error != undefined) {
        << error handling code here >>
        } else {
            StartPlayer(response.width, response.height, response.filename);
        }
    }  });
}

所以,在没有错误的情况下,调用后使用来自响应的文件名启动播放器。这就是我需要的。
我在Live HTTP Headers中重新检查了一次调用:

http://<< SITE_URL >>/ajaxdata.php
POST /ajaxdata.php HTTP/1.1
Host: << SITE_URL >>
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: << VIDEO_PAGE >>
Content-Length: 31
Cookie: << COOKIE VALUES >>
DNT: 1
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
    mod=videodata&vid=48901&res=640

HTTP/1.1 200 OK
Server: nginx/1.5.9
Date: Tue, 22 Apr 2014 16:30:06 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
Expires: Tue, 22 Apr 2014 16:30:05 GMT
Cache-Control: no-cache
Pragma: no-cache
Content-Encoding: gzip

因此,它使用特定参数调用 ajaxdata.php,并在响应中找到文件名。
然而,这个 Python 代码对我来说完全没有返回任何内容(无论是内容还是错误)。
import requests

url = "http://LALLALAA/ajaxdata.php"
data_video = {"mod": "videodata", "vid": "48901", 'res': '640'}

s = requests.Session()
s.post(login_url, data=login_data) # Authentication

content = s.post(url, data=data_video)
print content.content

变量内容只打印“Response [200]”
现在我完全被卡住了,如果有人能指出我犯的错误或我可以尝试的解决方案,我将不胜感激。

谢谢


3
最好从头开始尝试实验;例如s.post(url, data=data_video, headers={'X-Requested-With', 'XMLHttpRequest'})等。 - Martijn Pieters
1个回答

14

正如Martijn Pieters建议的那样,我一个一个地尝试标题,并发现这种组合现在有效:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest'
}

s = requests.Session()
s.post(login_url, data=login_data)

content = s.post(url, data=data_video, headers=headers)

我感谢所有人,特别是Martijn Pieters


2
如果页面受密码保护,并且ajax调用需要cookies,我们如何模拟ajax请求? - user1788736

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接