【发布时间】:2021-11-16 21:46:21
【问题描述】:
我想打开一个包含动态网址的新标签。我得到的 url 存储在 str 变量中,如下所示:
String str = WebPublish_URL.getText();
现在我想要一个使用getText() 方法的带有url 的标签。
【问题讨论】:
标签: selenium testing automation
我想打开一个包含动态网址的新标签。我得到的 url 存储在 str 变量中,如下所示:
String str = WebPublish_URL.getText();
现在我想要一个使用getText() 方法的带有url 的标签。
【问题讨论】:
标签: selenium testing automation
有 4 种方法可以做到这一点。在下面的示例中,我正在执行以下步骤,
https://google.com
facebook 文本并获取facebook URL
facebook。解决方案#1:获取URL 值并将其加载到现有浏览器中。
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
driver.get(facebookUrl);
解决方案#2:使用window handles。
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(facebookUrl);
解决方案#3:通过创建新的 driver 实例。不建议这样做,但它也是一种可能的方法。
driver = new ChromeDriver(options);
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
/*Create an another instance of driver.*/
driver = new ChromeDriver(options);
driver.get(facebookUrl);
使用 Selenium 4 更新:
driver.get("https://www.google.com/search?q=facebook");
String facebookUrl = driver.findElement(By.xpath("(//a[contains(@href,'facebook.com')])[1]")).getAttribute("href");
driver.switchTo().newWindow(WindowType.TAB);
driver.navigate().to(facebookUrl);
【讨论】:
.getText 是来自 网络元素 的 get the text。如果您的str 包含URL,并且您想打开一个新标签然后加载str containing URL,请尝试以下步骤:
打开一个新标签
((JavascriptExecutor) driver).executeScript("window.open()");
一旦打开,您也需要切换。
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
所以基本上,按顺序:
((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get(str);
【讨论】: