user6519393
user6519393

Reputation:

Getting current browser url using selenium and python and save it

Using selenium and python. I am trying to get a URL and save it by doing this:

driver = webdriver.Firefox()
driver.get("https://google.com")

elem = driver.find_element(By.XPATH, "/html/body/div/div[3]/div[1]/div/div/div/div[1]/div[1]/a")
elem.click()

url = driver.current_url
print url

url that prints is google.com and not the new clicked link which gmail. My question is, how can I get the second url and save it.

Upvotes: 0

Views: 1348

Answers (1)

alecxe
alecxe

Reputation: 473753

You are getting the current url before the new page is loaded. Add an Explicit Wait to, for instance, wait for the page title to contain "Gmail":

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("https://google.com")

# click "Gmail" link
elem = driver.find_element_by_link_text("Gmail")
elem.click()

# wait for the page to load
wait = WebDriverWait(driver, 10)
wait.until(EC.title_contains("Gmail"))

url = driver.current_url
print(url)

Also note how I've improved the way to locate the Gmail link.

Upvotes: 1

Related Questions