繁体   English   中英

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

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

我无法在chrome中打开新标签页。 我的要求是打开一个新选项卡执行某些操作然后关闭此新选项卡并返回旧选项卡。 下面的python代码在Firefox中有效但在Chrome中无效。 有人可以帮帮我吗?

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

猜猜这会有所帮助:

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

这段代码应该启动新的Chrome浏览器会话并在新标签页中打开空白页面

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

我无法通过driver.execute_script("window.open('URL');")打开带有所需URL的新选项卡driver.execute_script("window.open('URL');")

所以我改变了主意。

如果我们考虑将当前窗口切换到新窗口,则任何链接都将在新选项卡上开始。 我将通过driver.get(URL)打开新选项卡。 我需要使用的唯一方法是driver.switch_to_window(driver.window_handles[1])

当我们关闭新选项卡时,我们只需将窗口切换到主窗口: driver.switch_to_window(driver.window_handles[0])driver.switch_to_window(main_window)

顺便说一句,如果我们在关闭新选项卡后没有切换到主窗口,则会引发错误。

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