4

How can i use selenium to find the current url after clicking an element. I have this website: http://www.runningintheusa.com/Classic/View.aspx?RaceID=5622

I have the code(assuming all related libraries are imported)

def get_detail(x):
    dic = {}
    driver = webdriver.PhantomJS(path)
    driver.get(x)
    driver.find_element_by_id('ctl00_ctl00_MainContent_hypPrimaryURL').click()
    return driver.current_url
print get_detail('http://www.runningintheusa.com/Classic/View.aspx?RaceID=5622')

I ran the code and it only return the original url which is http://www.runningintheusa.com/Classic/View.aspx?RaceID=5622

How can i find the url after clicking the Race Website link on the site which is http://flagstaffbigs.org/dave-mckay-run.htm

V.Anh
  • 497
  • 3
  • 8
  • 15

2 Answers2

9

Is it because a new tab is opening, this will select the active newest tab.

driver.switch_to_window(driver.window_handles[-1])
return driver.current_url;
kparker
  • 161
  • 7
  • 1
    It worked but it took 45 sec to return the url, is there any way to shorten the process ? – V.Anh Jul 17 '17 at 12:33
1

I tried the website here and when you click the element you actually open another tab. So the driver.current_url returns the original url because it hasn't change, you have only created a new tab with the new URL.

What you need to do is change the driver to the new tab and get its URL, or change the link to open in the same tab.

Here is an example of switching to a new tab in Java.

To change the link to open in the same tab you can simply remove the target="_blank" from the HTML.

gnobre
  • 126
  • 7