使用新服务方法初始化selenium webdriver后无法交互 [Python]
我正在尝试用以下代码初始化一个Chrome的webdriver,并使用自定义的用户配置文件:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")
options.add_argument(r'user-data-dir=C:\Users\{User}\AppData\Local\Google\Chrome\User Data\Profile XY')
service = Service(executable_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe')
driver = webdriver.Chrome(options=options, service=service)
到目前为止,一切都很好。代码执行到这里时,会弹出一个新的Chrome窗口,并且选择了正确的用户配置文件。但是,在初始化webdriver之后的所有代码都不再执行了。例如,下面的代码就不会被执行。
print("This is a debug msg")
driver.get("https://google.com/")
所以我的问题是,在初始化之后,我该如何正确地与这个驱动程序互动,如果我不能再使用driver.doSomething()了?
任何帮助都将不胜感激。
附加信息:使用的是最新的Chrome和Selenium版本。
请查看上面的代码示例。
1 个回答
0
service = Service(executable_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe')
上面的说法不对。你需要在 executable_path
中提供 chromedriver.exe
的完整路径,而不是 chrome.exe
。
替代方案: 现在你不需要手动设置 chromedriver.exe
了。如果你使用的是最新的 selenium(v4.6.0
或更高版本),可以跳过在 executable_path
中设置路径。下面的代码可以参考:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("--start-maximized")
options.add_argument(r'user-data-dir=C:\Users\{User}\AppData\Local\Google\Chrome\User Data\Default')
service = Service()
driver = webdriver.Chrome(options=options, service=service)
print("This is a debug msg")
driver.get("https://google.com/")
控制台结果:
This is a debug msg
Process finished with exit code 0
想了解更多信息,可以参考这个答案 - https://stackoverflow.com/a/76463081/7598774