0

I'm practicing with selenium right now but I can't seem to get it to print the correct URL.

import time
from selenium import webdriver

driver = webdriver.Firefox()
home_page = ''
driver.get(home_page)


time.sleep(15)
for i in range(1,9):
    listing_page = driver.find_element_by_xpath('//*[@id="m_property_lst_cnt_realtor_more_'+str(i)+'"]').click()
    realtor_url = driver.find_element_by_xpath('//*[@id="lblMediaLinks"]/a').click()
    print(driver.current_url)
    driver.get(home_page)
    time.sleep(5)

I need the URL of the webpage that opens up when selenium clicks on the element in realtor_url. It instead prints the URL of the first click from listing_page.

(Note: webpage that is opened from realtor_url is a completely different website, if that helps)

4eller
  • 19
  • 6

2 Answers2

0

You need to switch to the newly opened window before printing the URL, then close the newly opened window and switch back to the original window.

// do the click that opens another window
WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == 2)
driver.switch_to_window(driver.window_handles[1])
print(driver.current_url)
driver.close()
driver.switch_to_window(driver.window_handles[0])

A couple other things...

  1. .click() returns void, i.e. nothing, so there's nothing ever stored in listing_page or realtor_url variables.

  2. sleep() is a bad practice. Don't use it. Google it to find out the details why. Replace sleep() with a relevant WebDriverWait.

JeffC
  • 22,180
  • 5
  • 32
  • 55
  • What it's doing is clicking on a real estate listing then from that page, clicks on the agents website and prints out the URL of their web page. There are 9 listings on the page so it goes through the row and does this for each. – 4eller Oct 10 '17 at 02:52
  • I see now. I missed the `i` in your first click statement. I added some details. – JeffC Oct 10 '17 at 03:25
  • No worries, I tinkered with the wait time for the second URL but the issue is that print(driver.current_url) prints the URL from the first instance rather than from the new webpage that I want it to. Both your and Kiran's answers cleared up a lot of frustration! Thank you :) – 4eller Oct 10 '17 at 03:33
  • If you still have issues with printing the wrong URL, you may need to use a wait to wait for the second window to open, e.g. `WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == 2)`. Added this to my answer. – JeffC Oct 10 '17 at 03:37
0

I believe you need to change the "focus"of the window in order to print the correct url. The current window handler may be pointing to the previous click and not changed focus to the new window. Try and get to change the "window handler". Every new window opened has a handler.

I hope this helps. window_handles Or this Handle multiple window in Python

EDIT:

The below should bring you to the latest open window.

driver.switch_to_window(driver.window_handles[-1])