Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening link in the new tab and switching between tabs (Selenium WebDriver + Python) [duplicate]

I have such code with comments:

import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys


browser = webdriver.Chrome()
browser.get("https://www.google.com?q=python#q=python")
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: 
browser.find_element_by_class_name("rc"))
first_link = first_result.find_element_by_tag_name("a")

# Save the window opener (current window, do not mistake with tab... 
not the same).
main_window = browser.current_window_handle

# Open the link in a new tab by sending keystrokes on the element.
first_link.send_keys(Keys.COMMAND + "t")

# Switch tab to the new tab, which we will assume is the next one on 
the right and put focus.
browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND + 
Keys.NUMPAD2)

# Close current tab.
browser.find_element_by_tag_name("body").send_keys(Keys.COMMAND + "w")

# Put the focus on the current window which will be the window opener.
browser.switch_to.window(main_window)

But it does not work (the script is hanging) -- first_link is not opening in the new tab. Any other thoughts about it? Thanks.

PS: I am on the macOS.

like image 980
Ratmir Asanov Avatar asked Dec 01 '22 15:12

Ratmir Asanov


2 Answers

You can use this code:

driver.execute_script("window.open('http://google.com', 'new_window')")

for switching:

driver.switch_to_window(driver.window_handles[0])

Refer this Answer.

like image 86
iamsankalp89 Avatar answered Dec 05 '22 11:12

iamsankalp89


The following code is working now:

from selenium import webdriver
from selenium.webdriver.support import ui
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains


browser = webdriver.Chrome()
browser.get("https://www.google.com?q=python#q=python")
first_result = ui.WebDriverWait(browser, 15).until(lambda browser: 
browser.find_element_by_class_name("rc"))
first_link = first_result.find_element_by_tag_name("a")

# Save the window opener (current window, do not mistake with tab... not the same).
main_window = browser.current_window_handle

# Open the link in a new tab by sending keystrokes on the element.
ActionChains(browser) \
.key_down(Keys.COMMAND) \
.click(first_link) \
.key_up(Keys.COMMAND) \
.perform()

browser.switch_to.window(browser.window_handles[1])

time.sleep(5)

# Close current tab.
browser.close()

time.sleep(5)

# Put the focus on the current window which will be the window opener.
browser.switch_to.window(main_window)

# Close the instance of the browser.
browser.quit()

Thanks for your help!

like image 24
Ratmir Asanov Avatar answered Dec 05 '22 13:12

Ratmir Asanov