使用 selenium,您可以执行任意 Javascript,包括 programmatically submit a form。
使用 Selenium Java 执行最简单的 JS:
if (driver instanceof JavascriptExecutor) {
System.out.println(((JavascriptExecutor) driver).executeScript("prompt('enter text...');"));
}
您可以使用 Javascript 创建 POST 请求,设置所需的参数和 HTTP 标头,然后提交。
// Javascript example of a POST request
var xhr = new XMLHttpRequest();
// false as 3rd argument will forces synchronous processing
xhr.open('POST', 'http://httpbin.org/post', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('login=test&password=test');
alert(xhr.response);
在现代最前沿的浏览器中,您还可以使用fetch()。
如果您需要将响应文本传递给 selenium,那么请使用 return this.responseText 或 return this.response 而不是 alert(this.responseText) 并将 execute_script(或 execute_async_script)的结果分配给变量(如果使用 python) .对于java,对应的executeScript()或executeAsyncScript()。
这是一个完整的python示例:
from selenium import webdriver
driver = webdriver.Chrome()
js = '''var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://httpbin.org/post', false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('login=test&password=test');
return xhr.response;'''
result = driver.execute_script(js);
result 将包含您的 JavaScript 的返回值,前提是 js 代码是同步的。将false 设置为xhr.open(..) 的第三个参数会强制请求是同步的。将第三个参数设置为 true 或省略它会使请求异步。
❗️ 如果您正在调用 asynchronous js 代码,请确保使用 execute_script 而不是 execute_async_script,否则调用将不会返回任何内容!
注意:如果您需要将字符串参数传递给 javascript,请确保始终使用 json.dumps(myString) 转义它们,否则当字符串包含单引号或双引号或其他棘手字符时,您的 js 将中断。