python接口自动化37-模拟ajax异步请求(X-Requested-With:XMLHttpRequest)
2021/6/2 22:25:20
本文主要是介绍python接口自动化37-模拟ajax异步请求(X-Requested-With:XMLHttpRequest),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
前言有些接口请求头部带上X-Requested-With:XMLHttpRequest ,返回数据是 json 。如果头部不加这个参数,返回数据是普通 html 文本。
这种头部带上X-Requested-With:XMLHttpRequest的是 Ajax 异步请求。
Ajax 即 “Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
那么服务器如何判断request来自Ajax请求(异步)还是传统http请求(同步)?
1、传统同步请求参数
accept */* accept-charset gb2312,utf-8;q=0.7,*;q=0.7 accept-encoding gzip,deflate accept-language zh-cn,zh;q=0.5 cache-control max-age=0 connection keep-alive cookie JSESSIONID=1A3BED3F593EA9747C9FDA16D309AF6B keep-alive 300 user-agent Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.15) Gecko/2009101601 Firefox/3.0.15 (.NET CLR 3.5.30729)
2、Ajax 异步请求方式
accept */* accept-charset gb2312,utf-8;q=0.7,*;q=0.7 x-requested-with XMLHttpRequest accept-encoding gzip,deflate accept-language zh-cn,zh;q=0.5 cache-control max-age=0 connection keep-alive cookie JSESSIONID=1A3BED3F593EA9747C9FDA16D309AF6B keep-alive 300 user-agent Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.15) Gecko/2009101601 Firefox/3.0.15 (.NET CLR 3.5.30729)
可以看到 Ajax 请求多了个 x-requested-with
场景案例登录禅道网站,输入账号和密码后
使用fiddler抓包看请求参数,头部会有个参数:X-Requested-With: XMLHttpRequest
,返回的是json数据: {"result":"success","locate":"\/zentao\/"}
使用requests发请求,如果头部不带参数:X-Requested-With: XMLHttpRequest
import requests # 作者-上海悠悠 QQ交流群:717225969 # blog地址 https://www.cnblogs.com/yoyoketang/ url = "http://49.235.x.x:8081/zentao/user-login.html" body = { "account": "admin", "password": "yoyo123456", "passwordStrength": 1, "referer": "/zentao/", "verifyRand": "1014015280", "keepLogin": 1 } r = requests.post(url, data=body) print(r.text) # 返回html # <html><meta charset='utf-8'/><style>body{background:white}</style><script>self.location='/zentao/'; # </script>
使用requests发请求, 头部带上参数:X-Requested-With: XMLHttpRequest
,模拟 Ajax 异步请求
import requests # 作者-上海悠悠 QQ交流群:717225969 # blog地址 https://www.cnblogs.com/yoyoketang/ url = "http://49.235.x.x:8081/zentao/user-login.html" h = { "X-Requested-With": "XMLHttpRequest" } body = { "account": "admin", "password": "yoyo123456", "passwordStrength": 1, "referer": "/zentao/", "verifyRand": "1014015280", "keepLogin": 1 } r = requests.post(url, headers=h, data=body) print(r.text) # 返回json # {"result":"success","locate":"\/zentao\/"}
此时就可以返回json数据了
这篇关于python接口自动化37-模拟ajax异步请求(X-Requested-With:XMLHttpRequest)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python