加载页面后,selenium获取当前URL

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

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

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

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

 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() { public Boolean apply(WebDriver d) { return (d.getCurrentUrl() != previousURL); } }; wait.until(e); currentURL = driver.getCurrentUrl(); System.out.println(currentURL); } 

第2页是在新的标签页/窗口中? 如果是这样,请使用以下代码:

 try { String winHandleBefore = driver.getWindowHandle(); for(String winHandle : driver.getWindowHandles()){ driver.switchTo().window(winHandle); String act = driver.getCurrentUrl(); } }catch(Exception e){ System.out.println("fail"); } 

我用selenium编码已经有一段时间了,但你的代码看起来还不错。 需要注意的一点是,如果找不到元素,但超时被传递,我认为代码将继续执行。 所以你可以这样做:

 boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0 

上面的布尔返回了什么? 你确定selenium实际导航到预期的页面吗? (这可能听起来像一个愚蠢的问题,但你实际上是在看页面改变…selenium可以远程运行,你知道……)