使用 selenium WebDriver 在网页中执行 javascript [英] Execute javascript within webpage with selenium WebDriver

查看:33
本文介绍了使用 selenium WebDriver 在网页中执行 javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 selenium WebDriver 在网页上执行 javascript 方法.我可以在页面上执行我自己的脚本,但不能从页面的 HTML 中调用该方法.这是 HTML

I am trying to execute a javascript method on a webpage with the selenium WebDriver. I am able to execute my own script on the page, but not call the method from the page's HTML. Here is the HTML

    function Search(){
        if(check(document.forms[0],"searchResults")){
        var fieldCode = "";
        var fieldText = "";

        if((document.forms[0].elements['prrSearchVO.selectedSearchCriteria.prrNumber'].value =="") && (!isPRRNoSelected()))
        {
            alert('PRR No. must be a selected field.');
            unSelectAllOptions(document.forms[0].availableFieldsListArray);
            unSelectAllOptions(document.forms[0].selectedFieldsList);
        }
        else
        {
            document.forms[0].excelRequested.value = "false";
            document.forms[0].action = "prrSearchResults.do";
            document.forms[0].submit();
        }
    }
} 

如果我尝试手动提交表单,它无法正确加载.我可以使用下面的代码执行我自己的 javascript.如何从页面执行搜索"功能?

If i attempt to submit the form manually it does not load properly. I can execute my own javascript using the code below. How can I execute the "Search" function from the page?

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('fromIssueDate').removeAttribute('readOnly')");

推荐答案

首先,除非您真的别无选择,否则不应使用 WebDriver 执行 javascript.为什么提交不起作用?你尝试了什么?根据我的经验,有时 click 不会触发表单提交,因此您可以在表单元素上使用 submit .请注意,如果您在非表单元素上 submit ,则它是无操作的.所以像下面这样的东西应该可以工作,

First of all you shouldn't execute javascript using WebDriver unless you really have no other option. Why doesn't the submit work? what did you try? In my experience sometimes click doesn't trigger form submission, so instead you use submit on the form element. Note that if you submit on a non-form element its a no-op. So something like below should work,

    WebElement email = driver.findElement(By.id("email"));
    WebElement password = driver.findElement(By.id("password"));
    WebElement submit = driver.findElement(By.id("submit"));
    email.sendKeys("John");
    email.password("foo");
    submit.submit();

回到你最初的问题,Search() 是一个全局函数吗?然后你可以做类似下面的事情,但是就像我说的,WebDriver 不建议你调用 javascript,因为这不是真实用户与你的应用程序交互的方式

Going back to your original question, is Search() a global function? Then you could do something like below, however like I said, WebDriver doesn't recommend you invoke javascript since that's not how real users would interact with your application

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.Search();");

这篇关于使用 selenium WebDriver 在网页中执行 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆