首页 > python模拟http请求,返回“浏览器不支持javascript,请设置您的浏览器开启javascript支持”

python模拟http请求,返回“浏览器不支持javascript,请设置您的浏览器开启javascript支持”

需求
写一个可以自动获取“腾讯微博开发平台”申请中的oauth_verifier参数值的脚本。
正常情况下,需要人工从浏览器地址栏复制oauth_verifier的值,这个可以模拟发送http请求包来解决,但是,好像其中有执行了js脚本,以前没碰到过,不知道怎么解决。

.

方便理解,我上传下可以执行文件demo

腾讯微博API Demo
当执行第2步的时候,会自动弹出一个网页,然后登录要授权的qq,接着就可以从浏览器地址栏中获取oauth_verifier参数的值
我想要将第2步获取oauth_verifier参数的值直接用python代码实现

使用python模拟浏览器发送http请求:
请求的url:

http://open.t.qq.com/cgi-bin/authorize?oauth_token=xxx&checkStatus=checked&checkType=authorize&sessionKey=xxx

正常情况下,应该返回如下响应:

<html>  
<head>  
<meta http-equiv="refresh" content="0;url=http://www.qq.com?oauth_token=xxx&oauth_verifier=mmmmm&openid=xxxx&openkey=xxx">  
</head>  
</html>

但是,我执行如下代码的时候,返回的是如下数据:

你的浏览器不支持javascript,请设置您的浏览器开启javascript支持!

python代码如下:

def GetCode():
    #Get参数
    params = {'oauth_token':'xxxx','checkStatus':'checked','checkType':'authorize','sessionKey':'xxx'}
    url = 'http://open.t.qq.com/cgi-bin/authorize'
    #http请求头
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",
        "Host":"open.t.qq.com",
        "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4",
        "Accept-Encoding":"gzip,deflate,sdch",
        "Referer":"http://xui.ptlogin2.qq.com/cgi-bin/qlogin?............",
        "Connection":"keep-alive",
        "Cookie":"...................................."
    }
    r = requests.get(url,params = params,headers=headers)
    print r.conten

http://open.t.qq.com/cgi-bin/authorize?oauth_token=xxx&checkStatus=checked&checkType=authorize&sessionKey=xxx
上面这个 URL 返回的是一个重定向,requests 碰到重定向会自动跟着跳转,
有可能它已经自动帮你跳转到 http://www.qq.com?oauth_token=xxx&oauth_verifier=mmmmm&openid=xxxx&openkey=xxx 这个 URL 上了。

官方描述:http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history

解决办法1:通过 Response.history 取得最终访问到的 url,然后解析出 oauth_verifier

解决办法2: 禁用重定向自动跳转功能
requests.get(url,params=params, headers=headers, allow_redirects=False)

P.S. 以上其实是猜测,requests 有没有

【热门文章】
【热门文章】