简体   繁体   English

由python webdriver在chrome浏览器中的selenium新选项卡

[英]selenium new tab in chrome browser by python webdriver

I am not being able to open a new tab in chrome. 我无法在chrome中打开新标签页。 My requirement is to open a new tab do some operation then close this new tab and come back to old tab. 我的要求是打开一个新选项卡执行某些操作然后关闭此新选项卡并返回旧选项卡。 The below python code worked in Firefox but not working in Chrome. 下面的python代码在Firefox中有效但在Chrome中无效。 Could anyone please help me? 有人可以帮帮我吗?

ActionChains(driver).key_down(Keys.CONTROL,body).send_keys('t').key_up(Keys.CONTROL).perform()

Guess this will be helpful: 猜猜这会有所帮助:

from selenium import webdriver
driver = webdriver.Chrome()
driver.execute_script("window.open('','_blank');")

This piece of code should start new Chrome browser session and open blank page in new tab 这段代码应该启动新的Chrome浏览器会话并在新标签页中打开空白页面

Use driver.execute_script("window.open('URL');") to open new tab with required URL 使用driver.execute_script("window.open('URL');")打开包含所需URL的新选项卡

I failed to open new tab with required URL by driver.execute_script("window.open('URL');") . 我无法通过driver.execute_script("window.open('URL');")打开带有所需URL的新选项卡driver.execute_script("window.open('URL');")

Therefore I changed my mind. 所以我改变了主意。

Any link will start on the new tab if we consider switching the current window to the new one. 如果我们考虑将当前窗口切换到新窗口,则任何链接都将在新选项卡上开始。 And I will open the new tab by driver.get(URL) . 我将通过driver.get(URL)打开新选项卡。 The only method I need to use is driver.switch_to_window(driver.window_handles[1]) . 我需要使用的唯一方法是driver.switch_to_window(driver.window_handles[1])

We simply switch the window to the main window, when we close the new tab: driver.switch_to_window(driver.window_handles[0]) or driver.switch_to_window(main_window) 当我们关闭新选项卡时,我们只需将窗口切换到主窗口: driver.switch_to_window(driver.window_handles[0])driver.switch_to_window(main_window)

By the way, it will raise an error if we don't switch to the main window after closing the new tab. 顺便说一句,如果我们在关闭新选项卡后没有切换到主窗口,则会引发错误。

from selenium import webdriver


driver = webdriver.Chrome()
driver.get("http://www.google.com/")

# save main_window
main_window = driver.current_window_handle

# obtain url of gmail on the home page of Google
addr = driver.find_element_by_xpath('//*[@id="gbw"]/div/div/div[1]/div[1]/a').get_attribute("href")

# open new blank tab
driver.execute_script("window.open();")

# switch to the new window which is second in window_handles array
driver.switch_to_window(driver.window_handles[1])

# open successfully and close
driver.get(addr)
driver.close()

# back to the main window
driver.switch_to_window(main_window)
driver.get(addr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM