I am writing a python script that uses BeautifulSoup to web scrape and then Selenium to navigate sites. After navigating to another site using the .click() on a link I want to use .current_url to get the site url to use for beautiful soup. The problem is that the .click() opens the link in a new tab so when I use current_url I get the url of the original site.
I tried using:
second_driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
to change tabs but it has no effect on the current_url function so it didn't work.
Simplified code:
second_driver = webdriver.Firefox()
second_driver.get(<the original url>)
time.sleep(1)
second_driver.find_element_by_class_name(<html for button that opens new tab >).click()
time.sleep(1)
url=second_driver.current_url
So I want url to be the new site after click not the original url
Thank you and sorry if its obvious I am a beginner.
You'll need to switch to the new tab. webrdiver.window_handles is a list of open tabs/windows. This snippet will switch you to the second open handle. If you want to go back to where you started, use [0]. If you want to always go to the last tab opened, use [-1]. If you try to switch to window_handles[1] before it exists, you'll raise an IndexError.
webdriver.switch_to_window(webdriver.window_handles[1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.