简体   繁体   English

如何在已经打开的 chrome 上运行 selenium python 脚本?

[英]How to run selenium python script on already opened chrome?

I know how to open a new window using selenium. But I want a new tab in the same window of chrome which I am using.我知道如何使用 selenium 打开一个新的 window。但是我想要在我正在使用的 chrome 的同一个 window 中有一个新标签。 How to do that?怎么做?

I already try:我已经尝试过:

from selenium import webdriver
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_experimental_option('debuggerAddress', 'localhost:9014')
driver = webdriver.Chrome(options=options)

try:
button = driver.find_element(By.CLASS_NAME, 'button')
button.click()
finally:
driver.quit()

You can achieve the opening/closing of a tab by the combination of keys: Ctrl + T or Ctrl + W您可以通过组合键实现打开/关闭选项卡: Ctrl + TCtrl + W

You can trigger this shortcut on body of the page, to open new tab within the window, like this:您可以在页面主体上触发此快捷方式,以在 window 中打开新选项卡,如下所示:

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

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

#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') 
# You can use (Keys.CONTROL + 't') on other OSs

# Load a page 
driver.get('http://stackoverflow.com/')
# Make the tests...

# close the tab
# (Keys.CONTROL + 'w') on other OSs.
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w') 


driver.close()

I hope this solves your problem.我希望这能解决你的问题。

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

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