如何使用 getText() 方法在浏览器地址栏中输入字符串,在 selenium webdriver java

How to enter string in browser address bar by using getText() method, in selenium webdriver java

我想打开一个包含动态 url 的新标签页。 url 我正在 str 变量中存储,如下所示:

String str = WebPublish_URL.getText();

现在我想要一个带有 url 的标签,使用 getText() 方法。

.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);

有 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);