【问题标题】:Selenium Webdriver - Best way to handle redirected URLSelenium Webdriver - 处理重定向 URL 的最佳方法
【发布时间】:2017-10-13 03:44:47
【问题描述】:

我有一个场景 - 当我点击我的测试 url(http://example.com) 上的按钮 (abcB) 时,它将被重定向到不同的 url(http://yourname.xyz),当我点击一个按钮(xyzB),它将返回到我通常的测试网址(http://example.com)并执行进一步的功能。请让我知道我该怎么做这个 Selenium Webdriver。

【问题讨论】:

  • 向我们展示您尝试过的代码。
  • 您面临的错误/问题在哪里?错误堆栈跟踪?

标签: java selenium selenium-webdriver webdriver


【解决方案1】:

这是一项简单直接的任务。我正在编写一些伪代码,因为您没有共享任何 html 代码以供参考。请使用以下代码并尝试。

driver.findElement(By.Xpath("<your xpath reference of button in first page>").click(); //to click on the button, and will navigate to target page
driver.getTitle();// to get the title to ensure you are in the correct page
driver.findElement(By.Xpath("<your xpath reference of button in second page>").click();
driver.getTitle();// to get the title to ensure that the browser is navigated back

【讨论】:

  • 好的,谢谢。由于 url 会改变,我认为我们需要以不同的方式处理它。
【解决方案2】:

如果我没看错的话,你的场景是这样的

driver.findElement(By.Xpath("Your xpath").click();
//wait for few second for loading site
    for (String windows : wd.getWindowHandles()) {

                wd.switchTo().window(windows);

                if (wd.getCurrentUrl().startsWith(Link + "xyz.com")) {

                //Your Operation
                   }
                if (wd.getCurrentUrl().startsWith(Link+"yzx.com")) {
    //Your Operation
                    }


            }

在这里我做了什么,我点击重定向链接。等待几秒钟的网站加载。重定向后,我返回愿望标签链接开始,你也可以在其中提供其他条件!!

希望对你有帮助

【讨论】:

    【解决方案3】:

    首先点击与标题匹配的第二个 URL 定位器,然后返回第一个 URL 在这里做同样的事情,你可以处理重定向的 URL

    你可以试试这个示例

    WebDriver driver=new FirefoxDriver();
      //Go to first URL and click on Download menu
      driver.get("http://www.seleniumhq.org");
     driver.findElement(By.xpath("//*[@id='menu_download']")).click();
     driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    
     //Click on  the Source code to redirect to second URL    
       WebElement sourceCode=driver.findElement(By.xpath(".//*[@id='mainContent']/p[1]/a[2]"));
     sourceCode.click();
    
    //Get the title of SecondURL and match
     String SecondUrl= driver.getTitle();
    if(SecondUrl.contains("GitHub - SeleniumHQ/selenium: A browser automation framework and ecosystem."))
     {
    System.out.println("welcome to second URL");
     }
    //come back to First URL by click on link
    driver.findElement(By.xpath("//a[contains(text(),'http://seleniumhq.org')]")).click();
    
    //Get the title of FirstURL and match
     String FirstUrl= driver.getTitle();;
    if(FirstUrl.contains("Selenium - Web Browser Automation"))
    {
     System.out.println("welcome to First URL");
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      • 2020-09-12
      • 1970-01-01
      相关资源
      最近更新 更多