search

Home  >  Q&A  >  body text

javascript - Using the click() method to click on a hyperlink in Java selenium is invalid and the page cannot be opened using window.open()

Using a.click(); is invalid. It is obviously OK at other times.

而且就算那我获取了href 在用js打开也没反应  这是为什么呢
 ((JavascriptExecutor)driver).executeScript("window.open('"+href+"')");  
    ((JavascriptExecutor)driver).executeScript("alert('"+href+"')");  
    
    
alert能弹出

But window.open() does not respond. It works if I type it directly on the console on the web page

PHP中文网PHP中文网2723 days ago1085

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-06-05 11:10:28

    window.open() opens a new tab, you need to switch handles. Here are two methods for your reference:

        public static void changeWindow(WebDriver driver){
            // 获取当前页面句柄
            String handle = driver.getWindowHandle();
            // 获取所有页面的句柄,并循环判断不是当前的句柄,就做选取switchTo()
            for (String handles : driver.getWindowHandles()) {
                if (handles.equals(handle))
                    continue;
                driver.switchTo().window(handles);
            }
        }
        public static void changeWindowTo(WebDriver driver,String handle){
            for (String tmp : driver.getWindowHandles()) {
                if (tmp.equals(handle)){
                    driver.switchTo().window(handle);
                    break;
                }
            }
        }

    As for the click, it may be because the element is not explicitly visible, or needs to be focused, or you are using Selenium improperly, but it is recommended to try js click

    reply
    0
  • Cancelreply