使用selenium,您可以执行任意Javascript,包括以编程方式提交表单.
使用Selenium Java执行最简单的JS:
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript("alert('hello world');");
}
Run Code Online (Sandbox Code Playgroud)
使用Javascript,您可以创建POST请求,设置所需的参数和HTTP标头,然后提交.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
alert(this.responseText);
};
xhr.send('login=test&password=test');
Run Code Online (Sandbox Code Playgroud)
如果需要将响应文本传递给selenium而不是alert(this.responseText)使用,return this.responseText并将executeScript()的结果分配给java变量.
这是python的完整示例:
from selenium import webdriver
driver = webdriver.Chrome()
js = '''var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
alert(this.responseText);
};
xhr.send('login=test&password=test');'''
driver.execute_script(js)
Run Code Online (Sandbox Code Playgroud)
注意:如果您需要将字符串参数传递给javascript,请确保始终使用它们来逃避它们
json.dumps(myString),否则当字符串包含单引号或双引号或其他棘手的字符时,js将会中断.
| 归档时间: |
|
| 查看次数: |
16338 次 |
| 最近记录: |