【问题标题】:How to enter string in browser address bar by using getText() method, in selenium webdriver java如何在selenium webdriver java中使用getText()方法在浏览器地址栏中输入字符串
【发布时间】:2021-11-16 21:46:21
【问题描述】:

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

String str = WebPublish_URL.getText();

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

【问题讨论】:

    标签: selenium testing automation


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 它对我有用。谢谢!
      • 听起来不错!有帮助吗?如果有,您能否接受此答案,以便将来的读者可以使用绿色。如果您想接受这个答案,请随时点击投票按钮旁边的复选标记。非常感谢您抽出宝贵时间并对此做出回应。
      猜你喜欢
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 2011-05-05
      • 2015-01-11
      • 2015-01-15
      • 2014-08-08
      • 2013-05-26
      相关资源
      最近更新 更多