0

我想在已经打开的窗口上运行 selenium python 脚本。因为我正在使用 get() 方法,所以它总是打开一个新窗口。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

path = r"C:\Program Files (x86)\chromedriver.exe"

driver = webdriver.Chrome(path)


driver.get("https://www.nike.ca/")

我对这个问题进行了很多搜索,发现了一个 youtube 视频https://www.youtube.com/watch?v=4F-laDV9Pl8 但这个视频是在 Java selenium 上的。

4

2 回答 2

2

我找到了解决方案。第 1 步:我们必须设置 chrome 应用程序的环境变量。为此,请转到 chrome 应用程序所在的目录。复制路径并将其粘贴到环境变量中。第 2 步:创建一个目录,您将在其中存储远程调试 chrome 窗口。像“D:\Selenium\Chrome_Test_Profile”。第 3 步:打开 CMD 并编写命令 chrome.exe -remote-debugging-port=9014 --user-data-dir="D:\Selenium\Chrome_Test_Profile" 第 4 步:使用以下代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.chrome.options import Options


path = r"C:\Program Files (x86)\chromedriver.exe"
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9014")
#Change chrome driver path accordingly
chrome_driver = path
driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options)
print (driver.current_url)
于 2020-11-04T13:20:13.200 回答
0

我让这个工作更简单。在确定 Chrome 的安装位置后,我打开命令提示符并输入:

C:>"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -remote-debugging-port=9014 --user-data-dir="C:\test\Chrome_Test_Profile"

因此,如果您愿意在启动浏览器时指定 Chrome 安装位置的完整路径,甚至不需要将 Chrome 安装目录添加到系统环境 PATH 变量中。如果需要,您甚至可以在桌面上为此启动规范创建一个快捷方式。

然后我的 Python 脚本是:

from selenium import webdriver

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

请注意,我的 Chrome 驱动程序安装在系统路径中的目录中,因此我不必将其位置指定为选项。

于 2020-11-04T13:26:33.603 回答