将Selenium Chrome Webdriver附加到已经打开的浏览器窗口?

时间:2020-05-12 13:49:18

标签: python python-3.x selenium selenium-webdriver browser

例如,某个用户启动了浏览器,然后启动了我的程序。我需要与此浏览器(不一定是Chrome)进行交互。 我在 Selenium 中遇到的问题有解决方案吗?还是另一种方式?

1)我看到了几乎合适的方法。通过以下命令从命令提示符启动Chrome:

chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\ChromeProfile"

然后使用以下代码附加启动的浏览器:

# PYTHON Example
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "localhost:1234")
#Change chrome driver path accordingly
chrome_driver = "C:\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chrome_driver, chrome_options=chrome_options)

但这是手动启动的浏览器

2)或在此link的第二种方式。但是从第一次尝试开始就有问题。

3)在GitHub上的issue中,我发现了this class,但是它对我不起作用。在该问题中写道,它仅使用Firefox(在ubuntu上)进行了测试。

有解决方案吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

考虑到软件开发实践,这是一个非常骇人听闻的解决方案,但这是可行的。

一旦您手动或使用脚本启动了Google chrome,就可以使用PyAutoGUI模块与其进行交互。我们可以将鼠标移到屏幕上的某个位置,单击然后键入。

打开chrome后的示例代码:

import pyautogui, time
pyautogui.PAUSE = 2

# x and y is the mouse position on your screen    
pyautogui.moveTo(x=410, y=79)
pyautogui.click()
# select all
pyautogui.hotkey('ctrl', 'a')
pyautogui.press(['delete'])
time.sleep(2)
pyautogui.typewrite("https://google.com")
pyautogui.press('enter')