59

I'm attempting to get the URL of the currently open page. I am using Selenium WebDriver and Java.

I am accessing the current URL via:

WebDriver driver = new WebDriver();
String url = driver.getCurrentUrl();

however, the URL does not appear to actually reflect where I currently am.

My current test case involves going to the NYT website and then clicking on the "Technology" link. However, url appears to always be http://www.nytimes.com/, regardless of the URL that is displayed in the address bar.

How do I actually access the value of the URL that's in the address bar so I can tell what page I'm actually on?

Karen
  • 885
  • 2
  • 7
  • 11
  • just curious why cant you directly access the technology link? why di you want to go to home page and click? – Kishore Jul 18 '12 at 20:24
  • My program is iteratively exploring the page by following links - but it would be useful to be able to know where it has actually been so that it doesn't click on the same links over and over again. – Karen Jul 18 '12 at 20:27
  • Using `HtmlUnitDriver` it, indeed, does not change the URL. Strange. In IE8 on Windows XP SP3, everything runs smoothly, though. What is your browser (did you try the others?), OS and Selenium version? – Petr Janeček Jul 18 '12 at 20:41
  • I know the OP asked about Java, but for Python/Robot Framework, at https://stackoverflow.com/questions/31833624/how-to-get-the-current-url-in-robot-framework someone recommended `GetLocation` – MarkHu Dec 23 '19 at 19:41

1 Answers1

28

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

T J
  • 42,762
  • 13
  • 83
  • 138
Avihai Marchiano
  • 3,837
  • 3
  • 38
  • 55
  • 11
    Sleep() should probably almost never be used for waiting for the page load. I think it's quite obvious why (network speed, cpu speed, web server response time, to name a few) and there are wait-related methods in the web driver for exactly those reasons, so always use those instead of sleep(). – Mladen B. Jun 14 '19 at 12:36