繁体   English   中英

如何在selenium中使用chrome webdriver下载python中的文件?

[英]How to use chrome webdriver in selenium to download files in python?

基于此处此处的帖子,我尝试在 selenium 中使用 chrome webdriver 来下载文件。 这是到目前为止的代码

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

chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_experimental_option("profile.default_content_settings.popups", 0)
chrome_options.add_experimental_option("download.prompt_for_download", "false")
chrome_options.add_experimental_option("download.default_directory", "/tmp")

driver = webdriver.Chrome(chrome_options=chrome_options)

但仅此一项就会导致以下错误:

WebDriverException: Message: unknown error: cannot parse capability: chromeOptions
from unknown error: unrecognized chrome option: download.default_directory
  (Driver info: chromedriver=2.24.417424 (c5c5ea873213ee72e3d0929b47482681555340c3),platform=Linux 4.10.0-37-generic x86_64)

那么如何解决这个问题呢? 我必须使用这种“能力”吗? 如果是这样,具体如何?

试试这个。 在windows上执行

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

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

options = Options()
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
})

我认为使用 WebDriver 保存任意文件(即图像)的最简单方法是执行将保存文件的 JavaScript。 完全不需要配置!

我使用这个库FileSaver.js轻松保存具有所需名称的文件。

from selenium import webdriver
import requests

FILE_SAVER_MIN_JS_URL = "https://raw.githubusercontent.com/eligrey/FileSaver.js/master/dist/FileSaver.min.js"

file_saver_min_js = requests.get(FILE_SAVER_MIN_JS_URL).content

chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome('/usr/local/bin/chromedriver', options=chrome_options)

# Execute FileSaver.js in page's context
driver.execute_script(file_saver_min_js)

# Now you can use saveAs() function
download_script = f'''
    return fetch('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=a010291124bf',
        {{
            "credentials": "same-origin",
            "headers": {{"accept":"image/webp,image/apng,image/*,*/*;q=0.8","accept-language":"en-US,en;q=0.9"}},
            "referrerPolicy": "no-referrer-when-downgrade",
            "body": null,
            "method": "GET",
            "mode": "cors"
        }}
    ).then(resp => {{
        return resp.blob();
    }}).then(blob => {{
        saveAs(blob, 'stackoverflow_logo.svg');
    }});
    '''

driver.execute_script(download_script)
# Done! Your browser has saved an SVG image!

一些提示:

  1. 铬和 chromedriver 应该有相同的版本。

    通常chromium包里面应该有chromedriver,你可以在安装目录中找到它。 如果您使用的是 ubuntu/debian,请执行dpkg -L chromium-chromedriver

  2. 拥有正确的 Chrome 首选项配置。

    正如 Satish 所说,使用options.add_experimental_option("prefs", ...)来配置 selenium+chrome。 但有时配​​置可能会随着时间而改变。 获得最新和可行的首选项的麻烦方法是在chromium config 目录中检查它。 例如,

    • 在 Xorg 桌面上启动一个 Chromium
    • 更改菜单中的设置
    • 戒掉铬
    • ~/.config/chromium/Default/Preferences找出真实的设置
    • 阅读它,挑选出您需要的确切选项。

就我而言,代码是:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

options = webdriver.ChromeOptions()
options.gpu = False
options.headless = True
options.add_experimental_option("prefs", {
    "download.default_directory" : "/data/books/chrome/",
    'profile.default_content_setting_values.automatic_downloads': 2,
    })

desired = options.to_capabilities()
desired['loggingPrefs'] = { 'performance': 'ALL'}
driver = webdriver.Chrome(desired_capabilities=desired)

对于 mac os 中的 chrome,download.defaultdirectory 对我不起作用,幸运的是savefile.default_directory工作。

prefs = {
    "printing.print_preview_sticky_settings.appState": json.dumps(settings),
    "savefile.default_directory": "/Users/creative/python-apps",
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "download.safebrowsing.enabled": True
}

从您的例外情况来看,您正在使用chromedriver=2.24.417424

您使用的是什么版本的 Selenium 和 Chrome 浏览器?

我尝试了以下代码:

  • 硒 3.6.0
  • 铬驱动程序 2.33
  • 谷歌浏览器 62.0.3202.62(官方版本)(64 位)

它有效:

from selenium import webdriver

download_dir = "/pathToDownloadDir"
chrome_options = webdriver.ChromeOptions()
preferences = {"download.default_directory": download_dir ,
               "directory_upgrade": True,
               "safebrowsing.enabled": True }
chrome_options.add_experimental_option("prefs", preferences)
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=r'/pathTo/chromedriver')

driver.get("urlFileToDownload");

确保您使用的是 chromedriver 支持的浏览器(从这里开始,应该是Chrome v52-54 )。

一个不能设置“download.default_directory”可能是你在文件〜/的.config /用户dirs.dirs有一个系统变量XDG_DOWNLOAD_DIR的原因

您可以从该文件中删除变量,或者在运行程序之前将其设置为您喜欢的任何内容。

我找了两天的解决方案......

我的软件设置:

  • Ubuntu 仿生,18.04.5 LTS
  • chromedriver.86.0.4240.22.lin64
  • 蟒蛇 3.9
  • 硒 3.141.0
  • 碎片 0.14.0

你不能使用requests库吗?

如果是这样,这里有一个例子:

import re
import requests

urls = [ '...' ]

for url in urls:
  # verify = False ==> for HTTPS requests without SSL certificates
  r = requests.get( url, allow_redirects = True, verify = False )

  cd = r.headers.get( 'content-disposition' )
  fa = re.findall( 'filename=(.+)', cd )

  if len( fa ) == 0:
    print( f'Error message: {link}' )
    continue

  filename = fa[ 0 ]

  f = open( os.path.join( 'desired_path', filename ), 'wb' )
  f.write( r.content )
  f.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM