Selenium不会在新标签页中打开新网址(Python和Chrome)

时间:2016-05-07 12:33:29

标签: python google-chrome selenium

我想使用Selenium WebDriver& amp ;;在不同的标签中打开相当多的网址。蟒。

我不确定出了什么问题:

driver = webdriver.Chrome()
driver.get(url1)
time.sleep(5)
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL+'t')
url2 = 'https://www.google.com'
driver.get(item2)

我查阅了教程,在我看来好像这段代码应该做我想要的。实际发生的是浏览器打开,url1打开它应该打开一个新选项卡,因为它应该但是 url2然后加载到原始选项卡而不是新选项卡(即使新选项卡看起来是活跃的)。

(我正在使用Chrome,因为在使用Firefox时我根本无法加载任何网址.Firefox打开但未获取请求的网址。我试图找到解决方案,但无济于事。)

我可以在代码中更改任何内容以在新标签页中打开新网址吗?

感谢您的帮助!

4 个答案:

答案 0 :(得分:11)

ChromeDriver中存在阻止ctrl / command + T工作的错误:

作为一种解决方法,您可以执行的操作是在新标签页中打开链接,然后使用switch_to.window() 切换到新窗口。工作样本:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

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

# open a link in a new window
actions = ActionChains(driver)
about = driver.find_element_by_link_text('About')
actions.key_down(Keys.CONTROL).click(about).key_up(Keys.CONTROL).perform()

driver.switch_to.window(driver.window_handles[-1])
driver.get("https://stackoverflow.com")

现在,最后一个driver.get()将在新打开的标签页中执行。

答案 1 :(得分:10)

这是一种独立于平台的简单方法:

代码:

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

切换回原始标签:

代码:

driver.switch_to_window(driver.window_handles[0])

检查当前标题以确保您在右页:

代码:

driver.title

其他一切,玩得开心!

答案 2 :(得分:8)

打开新窗口的另一种方法是使用JavaScript和窗口处理程序在它们之间切换。

driver = webdriver.Chrome()

# Open a new window
# This does not change focus to the new window for the driver.
driver.execute_script("window.open('');")

# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")

# close the active tab
driver.close()

# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("http://google.se")

# Close the only tab, will also close the browser.
driver.close()

如果您在执行时查看浏览器,看起来新窗口会有焦点,但对于webdriver,它不会。不要被视觉所欺骗。还要记住在关闭选项卡时选择新的窗口处理程序,因为它会将driver.current_window_handle设置为

selenium.common.exceptions.NoSuchWindowException: 
    Message: no such window: target window already closed from unknown error: web view not found
  (Session info: chrome=<Your version of chrome>)
  (Driver info: chromedriver=<Your chrome driver version> (<string of numbers>),platform=<Your OS>)

.close()上如果您尝试在该阶段对驱动程序执行操作,则会抛出该错误。

答案 3 :(得分:0)

为此,您需要最大限度地利用Chrome

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

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

e = driver.find_element_by_tag_name("body")
ActionChains(driver).key_down(Keys.CONTROL).click(e).send_keys("k").key_up(Keys.CONTROL).perform()

这里key_down(Keys.CONTROL)将按住ctrl键,以使焦点集中在页面上,我单击页面正文,然后单击k