加载页面后,selenium获取当前URL [英] selenium get current url after loading a page

查看:723
本文介绍了加载页面后,selenium获取当前URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用Selenium Webdriver。我想在点击下一步按钮后从第1页到第2页获取当前网址。这是我的代码:

I'm using Selenium Webdriver in Java. I want to get the current url after clicking the "next" button to move from page 1 to page 2. Here's the code I have:

    WebDriver driver = new FirefoxDriver();
    String startURL = //a starting url;
    String currentURL = null;
    WebDriverWait wait = new WebDriverWait(driver, 10);

    foo(driver,startURL);

    /* go to next page */
    if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
        driver.findElement(By.xpath("//*[@id='someID']")).click();  
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='someID']")));
        currentURL = driver.getCurrentUrl();
        System.out.println(currentURL);
    }   

我有等待页面的隐式和显式等待调用在我获得当前网址之前完全加载。但是,它仍然打印出第1页的网址(预计它将成为第2页的网址)。

I have both the implicit and explicit wait calls to wait for the page to be fully loaded before I get the current url. However, it's still printing out the url for page 1 (it's expected to be the url for page 2).

推荐答案

就像你说的那样,因为下一个按钮的xpath在每个页面上是相同的,所以它不起作用。它的编码工作方式是它等待元素显示,但由于它已经显示,因此隐式等待不适用,因为它根本不需要等待。为什么不使用url更改的事实,因为从您的代码中单击下一个按钮时它似乎会更改。我做C#,但我想在Java中它会是这样的:

Like you said since the xpath for the next button is the same on every page it won't work. It's working as coded in that it does wait for the element to be displayed but since it's already displayed then the implicit wait doesn't apply because it doesn't need to wait at all. Why don't you use the fact that the url changes since from your code it appears to change when the next button is clicked. I do C# but I guess in Java it would be something like:

WebDriver driver = new FirefoxDriver();
String startURL = //a starting url;
String currentURL = null;
WebDriverWait wait = new WebDriverWait(driver, 10);

foo(driver,startURL);

/* go to next page */
if(driver.findElement(By.xpath("//*[@id='someID']")).isDisplayed()){
    String previousURL = driver.getCurrentUrl();
    driver.findElement(By.xpath("//*[@id='someID']")).click();  
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    ExpectedCondition e = new ExpectedCondition<Boolean>() {
          public Boolean apply(WebDriver d) {
            return (d.getCurrentUrl() != previousURL);
          }
        };

    wait.until(e);
    currentURL = driver.getCurrentUrl();
    System.out.println(currentURL);
} 

这篇关于加载页面后,selenium获取当前URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆