• 欢迎访问IT乐园(o゚▽゚)o
  • 推荐使用最新版火狐浏览器和Chrome浏览器访问本网站。

python 模拟 ajax 请求

python fhy 6年前 (2017-11-10) 8714次浏览 0个评论

一次普通 post 请求 header 信息如下:

Accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.9,en;q=0.8
Connection:keep-alive
Content-Length:0
Content-Type:application/json
Cookie:....
Host:192.168.4.112:4001
Origin:chrome-extension://ecjfcmddigpdlehfhdnnnhfgihkmejin
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36

http ajax 请求头信息如下:

Accept:application/json
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.9,en;q=0.8
Connection:keep-alive
Content-Length:0
Content-Type:application/json
Cookie:.....
Host:192.168.4.112:4001
Origin:chrome-extension://ecjfcmddigpdlehfhdnnnhfgihkmejin
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36
x-requested-with:XMLHttpRequest

发现 ajax 请求头信息中多了一个 :
x-requested-with:XMLHttpRequest 参数

使用 python requests 模拟:

#!/usr/bin/python3
#-*- coding:utf-8 -*-

import requests
import json

def uptest():
    # 模拟 ajax 请求头
    header = {'x-requested-with': 'XMLHttpRequest'}
    url = "http://192.168.4.112:4001/aatapi/default/logout.html"

    post = {'1':2}
    rs = requests.post(url, data=post, headers=header)
    jsonen = rs.content.decode('utf-8-sig')
    try:
        strj = json.loads(jsonen)
    except Exception as err:
        # 返回值不是 json 类型
        print(err)
        print(rs.content)
        print('程序出现错误,停止运行')
        exit()

    # 格式化输出 json
    print(json.dumps(strj, ensure_ascii=False, sort_keys=False, indent=4))

uptest()

当然你可以在 headers 中添加更多参数,来模拟浏览器请求


IT 乐园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python 模拟 ajax 请求
喜欢 (6)
关于作者:
九零后挨踢男
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址