python操作已经打开的网页标签_Selenium不会在新标签页中打开新的网址(Python和Chrome)...

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)

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).

(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.)

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

Thanks for your help!

解决方案

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

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")

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值