How to force Selenium to open a link in a new window?

霸气de小男生 提交于 2020-12-22 18:49:19

问题


I need to open a link on a webpage in a new Chrome Window. There was already a question but this appears to be for RC. I tried driver.getUserWindow().open("http....."); But it is not working. May be there is a way to force Chrome to do that for all links? Ideally, i would like to know how to force a driver to open a link in a new window. (i am using java and OS Windows 7


回答1:


You can use Actions class to perform this.

Actions act = new Actions(driver);
WebElement onElement = Your element on which action has to be performed;
act.contextClick(onElement).perform();
act.sendKeys("w").perform();  // If you want the link to open in new tab then use T instead of w

Hope this helps. Happy coding.




回答2:


I don't know what language/OS you use, but here is how you can open link in new window on OS X with Ruby and WebDriver:

link = driver.find_element(:tag_name => 'a')
action = driver.action
key = :command # replace with :control on Win/Linux
action.key_down(key)
action.click(link)
action.key_up(key)
action.perform

This will open link in new tab. If you need new window, you should use :shift key.

You can also override click method for element, so it always opens links in new window.




回答3:


You can use the JS executor method for opening the link from new Tab

public void openFromNewTab(WebElement element) {

    ((JavascriptExecutor) driver).executeScript("window.open('" + element.getAttribute("href") + "','_blank');");
}


来源:https://stackoverflow.com/questions/19151095/how-to-force-selenium-to-open-a-link-in-a-new-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!