方法getCurrentUrl();返回错误的网址

时间:2018-05-22 04:05:17

标签: java selenium selenium-webdriver

我实际上刚开始用Selenium学习Java,我无法收到当前的URL。 Selenium返回起始URL,而不是当前的URL。

看起来,MyComponent[File]不起作用,或者我做错了什么?

implicitlywait()

4 个答案:

答案 0 :(得分:1)

点击“使用条款”链接后,您必须添加一些明确的等待,否则添加一些延迟。

修改后的代码:

driver.findElement(By.linkText("Terms of Use")).click();
//Added Newly
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains("Terms"));

String currentURL = driver.getCurrentUrl();

答案 1 :(得分:1)

这是一种预期的行为,因为您点击了"使用条款"的iframe,不会重定向您的网址(只需更改iframe)

enter image description here

我建议使用xpath找到所需的元素:

WebElement element = driver.findElement(By.xpath("/html[@class=' video no-videoautoplay']/body/div[@class='view-school']/footer[@class='bottom-menu bottom-menu-inverse']/div[@class='container']/div[@class='row']/div[@class='col-xs-12 col-sm-4 col-md-4 footer-column'][2]/ul[@class='list-unstyled']/li[1]/a"));

答案 2 :(得分:0)

如果标题匹配,则可以与标题匹配,然后打印当前网址,它始终为您提供正确的网址

public static void main(String[] args) throws InterruptedException {
System.out.println("Ready to launch the browser");
System.setProperty("webdriver.chrome.driver", "C:/Users/sankalp.gupta/Desktop/JAVASELN/chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://learn.letskodeit.com/p/practice");

WebElement benzRadioBtn = driver.findElement(By.id("benzradio"));
benzRadioBtn.click();

WebElement hondaRadioBtn = driver.findElement(By.id("hondaradio"));
hondaRadioBtn.click();
WebElement bmwRadioBtn = driver.findElement(By.id("bmwradio"));
bmwRadioBtn.click();
WebElement benzCheckBox = driver.findElement(By.id("benzcheck"));
benzCheckBox.click();
Select dropdown = new Select (driver.findElement(By.id("carselect")));
dropdown.selectByValue("honda");
WebElement element = driver.findElement(By.id("product"));
System.out.println(element.getText());

driver.findElement(By.linkText("Terms of Use")).click();
if(driver.getTitle().contains("Practice | Let's Kode It"))
    {
        System.out.println(driver.getCurrentUrl());

    }
}

答案 3 :(得分:0)

正如您在上一行中调用了click(),在检索 URL 旁边,您需要将 WebDriverWait ExpectedConditions 方法urlContains(java.lang.String fraction)如下:

new WebDriverWait(driver, 20).until(ExpectedConditions.urlContains("partial_text_of_url"));
System.out.println(driver.getCurrentUrl());

注意:您需要删除implicitlywait(),因为根据documentation

  

不要混合隐式和显式等待。这样做会导致不可预测的等待时间。例如,设置10秒的隐式等待和15秒的显式等待可能会导致20秒后发生超时。