使用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将会中断。



