如何使用Chrome中的Selenium + Python绑定控制文件下载

Dr.*_*ade 8 google-chrome file download python-2.7 selenium-webdriver

在哪里可以找到描述我可以与Selenium和Chrome网络浏览器一起使用的选项的文档?我想在Web浏览器中打开一个链接(获取凭据)但不要下载相应的文件(.pdf或.tiff或.jpeg).我在Windows 7笔记本电脑上使用Python 2.7,selenium 3.0.1和Chrome版本54.0.2840.99(以及chromedriver.exe).

# Chrome web browser.
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')  
#options.add_argument('--disable-download-notification') #doesn't seems to work 
#options.add_experimental_option("prefs", {"download.default_directory","C:\Users\xxx\downloads\Test"}) # doesn't work
#options.add_experimental_option("prefs", {"download.prompt_for_download": False}) # doesn't seems to work
#options.add_experimental_option("prefs", {'profile.default_content_settings': {'images': 2}})# this will disable image loading in the browser
options.add_argument("user-agent="+user_agent_profile)
driver_main = webdriver.Chrome(chrome_options=options)

# Opening the web application portail.
driver_main.get("https://my_link")
Run Code Online (Sandbox Code Playgroud)

我找到了很多关于这个主题的讨论,但没有一个解决方案有效.例如:

add_experimental_option("prefs", {"download.default_directory","C:\Users\xxx\downloads\Test"})
Run Code Online (Sandbox Code Playgroud)

不适合我.

同样的:

add_experimental_option("prefs", {"download.prompt_for_download": False})
Run Code Online (Sandbox Code Playgroud)

(我也尝试"假").

而:

add_argument("user-agent="+user_agent_profile)
Run Code Online (Sandbox Code Playgroud)

似乎工作!

我不确定是什么问题

我得到的问题是,每当我打开名称文件(1)文件(2)....文件(99)的链接时,它开始下载文件,然后从100开始,它会打开一个弹出窗口"另存为" .所以我想要么根本不下载文件或者能够将它移动到"回收站"中的特定文件夹中.

如何找到与add_argument和add_argument一起使用的选项?我试着看看Chrome://关于/但我看不到直接的信件.

非常感谢.

干杯.

法比安.

Flo*_* B. 17

您为默认目录声明的路径无效.要么逃避反斜杠要么提供文字字符串.

options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
  "download.default_directory": r"C:\Users\xxx\downloads\Test",
  "download.prompt_for_download": False,
  "download.directory_upgrade": True,
  "safebrowsing.enabled": True
})
driver = webdriver.Chrome(chrome_options=options)
Run Code Online (Sandbox Code Playgroud)

以下是可用的首选项:

https://cs.chromium.org/chromium/src/chrome/common/pref_names.cc

  • 如果要下载PDF,则以下行在选项中很重要:`“ plugins.always_open_pdf_externally”:是,`它类似于选中的菜单设置/隐私-内容设置/ PDF文档-在默认的PDF查看器应用程序中打开PDF文件(复选框) (3认同)
  • 如果要下载PDF,则以下行在选项中很重要:`“ plugins.always_open_pdf_externally”:是,`它类似于选中的菜单设置/隐私-内容设置/ PDF文档-在默认的PDF查看器应用程序中打开PDF文件(复选框) (2认同)