Python Selenium headless不使用自定义配置文件选择

Python Selenium headless不使用自定义配置文件选择,python,selenium,google-chrome,selenium-webdriver,Python,Selenium,Google Chrome,Selenium Webdriver,下面是我正在使用的代码——我试图使其尽可能简洁 import selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options import bs4 options=Options() #options.add_argument('--headless') # Works while not headless? options.add_argument('--disabl

下面是我正在使用的代码——我试图使其尽可能简洁

import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

import bs4

options=Options()
#options.add_argument('--headless') # Works while not headless?
options.add_argument('--disable-gpu')  # Last I checked this was necessary.
options.add_argument("--user-data-dir=profiles\\") #Keeps login data
options.add_argument("--profile-directory=Profile 1")

driver=webdriver.Chrome(chrome_options=options)
driver.get("http://www.google.com")
html=driver.page_source
soup=bs4.BeautifulSoup(html, "html.parser")

print(soup)
主要问题源于
--user data dir
--profile directory
参数。在我的测试示例中,当前目录中有一个自定义的chrome配置文件(通常位于
C:\Users\User\AppData\Local\Google\chrome\User Data
),用于将其与当前运行的任何chrome会话分开

如果在使用上述参数时启用了
--headless
参数,则驱动程序将挂起(CMD将保持不变,并且不会在Python命令行上生成输出)。但是,如果未启用,窗口将弹出并按预期运行

但是,
--headless
在使用上述默认目录中的任何配置文件时都可以工作

这是控制台输出

[0120/222514.611:ERROR:gpu_process_transport_factory.cc(967)] Lost UI shared context.

DevTools listening on ws://127.0.0.1:59961/devtools/browser/ee317ed6-93c7-47c2-b26d-63647980ba0d
[0120/222514.619:ERROR:devtools_http_handler.cc(289)] Error writing DevTools active port to file
[0120/222514.624:ERROR:cache_util_win.cc(19)] Unable to move the cache: 0
[0120/222514.625:ERROR:cache_util.cc(140)] Unable to move cache folder profiles\Default\GPUCache to profiles\Default\old_GPUCache_000
[0120/222514.625:ERROR:disk_cache.cc(184)] Unable to create cache
[0120/222514.625:ERROR:shader_disk_cache.cc(622)] Shader Cache Creation failed: -2
因此,Chromium似乎在某个地方假设我正在使用
Default
配置文件,而实际上我没有指定


有人有什么建议吗?提前谢谢

我可以通过添加以下选项来运行您的代码

options.add_argument('--remote-debugging-port=45447')
如果没有它,代码将挂起大约一分钟,然后抛出以下错误:

WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist
为我指出解决方案的评论摘录:

当您将--remote debuging port=0发送到Chrome时,devtools会选择 它自己的端口并将其作为文件写入chrome::DIR_USER_数据 命名为“DevToolsActivePort”

基本上,一旦端口设置为默认值0以外的值,就不需要检查DevToolsActivePort文件。 完整的注释和错误如下:


希望这有帮助

我通过关闭命令提示符并在管理员模式下重新打开它(右键单击cmd.exe并单击以管理员身份运行),解决了此错误


其他方法都不起作用。

我添加了该选项,出现了相同的错误-但我认为您可能有问题。你能编辑以显示你使用的片段吗?这样我就可以尝试准确地重新创建了?@ConstantlyConfused我在你的脚本中添加的唯一一行是我在回答中提到的那行,我也取消了headless arg的注释。在这种情况下,这似乎更像是一个环境问题。你能提供更多关于如何配置环境的详细信息吗?我已经更新了chromedriver.exe,虽然出现了相同的错误,但webdriver似乎可以正常工作。非常感谢您的帮助。这删除了WebDriverException,尝试并确认了这一点。