Selenium 不会在新选项卡中打开新 URL(Python 和 Chrome) [英] Selenium won't open a new URL in a new tab (Python & Chrome)

查看:42
本文介绍了Selenium 不会在新选项卡中打开新 URL(Python 和 Chrome)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Selenium WebDriver & 在不同的选项卡中打开相当多的 URL蟒蛇.

I want to open quite a few URLs in different tabs using Selenium WebDriver & Python.

我不确定出了什么问题:

I am not sure what is going wrong:

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 然后加载原始标签而不是新标签(即使新标签似乎是主动的).

I looked up tutorials and it seems to me as though this code should do what I want. What actually happens is the browser opens, url1 opens as it should, a new tab opens as it should but url2 then loads in the original tab instead of the new one (even though the new tab appears to be the active one).

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

(I am using Chrome because when using Firefox I can't get it to load any URLs at all. Firefox opens but does not get the url requested. I have tried to find a solution to this but to no avail.)

是否可以在代码中进行任何更改以获取在新标签页中打开的新 URL?

Is there anything I can change in my code to get the new URL to open in the new tab?

感谢您的帮助!

推荐答案

ChromeDriver 中存在一个错误,导致 ctrl/command+T 无法正常工作:

There is a bug in ChromeDriver that prevents ctrl/command+T from working:

作为一种解决方法,您可以做的是在新选项卡中打开一个链接,然后使用 switch_to.window()切换到一个新窗口.工作样本:

What you can do, as a workaround, is to open a link in a new tab and then switch to a new window using the switch_to.window(). Working sample:

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() 将在新打开的选项卡中执行.

Now the last driver.get() would be performed in a newly opened tab.

这篇关于Selenium 不会在新选项卡中打开新 URL(Python 和 Chrome)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆