栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Selenium中发出POST请求而不填写表格?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Selenium中发出POST请求而不填写表格?

使用selenium,您可以执行任意Javascript,包括以编程方式提交表单。

使用Selenium Java最简单的JS执行:

if (driver instanceof JavascriptExecutor) {    System.out.println(((JavascriptExecutor) driver).executescript("prompt('enter text...');"));}

使用Javascript,您可以创建POST请求,设置所需的参数和HTTP标头,然后提交。

var xhr = new XMLHttpRequest();// false as 3rd argument will forces synchronous processingxhr.open('POST', 'http://httpbin.org/post', false);xhr.setRequestHeader('Content-type', 'application/x-www-form-urlenpred');xhr.send('login=test&password=test');alert(xhr.response);

如果您需要传递给硒响应文本,则可以代替

alert(this.responseText)
使用
returnthis.responseText
returnthis.response
将execute_script(python)(针对Java的executescript())的结果分配给变量。

这是python的完整示例:

from selenium import webdriverdriver = webdriver.Chrome()js = '''var xhr = new XMLHttpRequest();xhr.open('POST', 'http://httpbin.org/post', false);xhr.setRequestHeader('Content-type', 'application/x-www-form-urlenpred');xhr.send('login=test&password=test');return xhr.response;'''result = driver.execute_script(js);

result
如果js代码是同步的,它将包含Javascript的返回值。设置
false
为第三个参数以
xhr.open(..)
强制请求同步。将第3个arg设置为
true
或忽略它会使请求异步,这将需要
xhr.onload= function({alert(this.responseText);};
处理结果。

注意:如果需要将字符串参数传递给javascript,请确保始终使用来转义它们

json.dumps(myString)
,否则当字符串包含单引号或双引号或其他棘手的字符时,js将会中断。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370775.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号