【问题标题】:Python 3 Chrome Selenium Keep Downloaded Jar FilePython 3 Chrome Selenium 保持下载的 Jar 文件
【发布时间】:2021-05-11 18:28:21
【问题描述】:

我正在使用 Selenium、Chrome 和 Python 3。

这就是我正在做的一切设置

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

chrome_options = Options()

options = webdriver.ChromeOptions()

prefs = {
    "download.default_directory": r"C:\Download\Dir",
    "download.directory_upgrade": "true",
    "download.prompt_for_download": "false",
    "disable-popup-blocking": "true",
    'download.neverAsk.saveToDisk':   'application/octet-stream, application/json, jar, ' +
                                                'text/comma-separated-values, text/csv, application/csv, ' +
                                                'application/excel, application/vnd.ms-excel, ' +
                                                'application/vnd.msexcel, text/anytext, text/plaintext, ' +
                                                'image/png, image/pjpeg, image/jpeg, application/zip',
    "safebrowsing.enabled": True
}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=options)
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-software-rasterizer')
chrome_options.add_argument('--safebrowsing-disable-download-protection')

然后我导入了一些凭据机密,以及一些网站导航以获取要下载的文件。

然后,我点击链接下载文件:

# Click Upgrade Jar File
driver.find_element_by_xpath('//a[@id="accordionPanel:j_id_3a:1:j_id_3j"]').click()

我的问题就在这里。 Chrome 会在我下载 jar 文件后询问我是否要保留它。



我已经阅读了很多文档,但我不明白如何才能规避这一点。我认为应该将其添加到 prefschrome_options.add_argument 但到目前为止,我找到的选项都没有运气。


更新 01:

一点更新,我能够让它“静默”工作,这允许您绕过“保持”按钮,但我还没有找到一个解决方案,可以绕过“保持”按钮,当你'重新查看 GUI。

options = webdriver.ChromeOptions()

prefs = {
    "download.default_directory": r"C:\Download\Dir",
    "download.directory_upgrade": "true",
    "download.prompt_for_download": "false",
    "disable-popup-blocking": "true",
    "safebrowsing.enabled": False,
    "default_content_settings": "contentSettings",
    "download": "download"
}
options.add_experimental_option("prefs", prefs)
options.add_argument("--headless")
options.add_argument("--disable-notifications")
options.add_argument('--disable-gpu')
options.add_argument('--disable-software-rasterizer')
driver = webdriver.Chrome(options=options)
options.add_argument('--safebrowsing-disable-download-protection')

更新 02

改编自评论的代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import os

# Secrets
user_id = [grabs from a function that queries secrets]
user_password = [grabs from a function that queries secrets]
download_dir = "C:\Download\Dir"

options = Options()
options.add_argument("--disable-infobars")
options.add_argument("start-maximized")
options.add_argument("--disable-extensions")
options.add_argument("--disable-popup-blocking")

# disable the banner "Chrome is being controlled by automated test software"
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches", ['enable-automation'])


prefs = {
    "download.default_directory": r"C:\Download\Dir",
    'download.prompt_for_download': False,
    'download.extensions_to_open': 'jar',
    'safebrowsing.enabled': True
}

capabilities = DesiredCapabilities().CHROME
options.add_experimental_option('prefs', prefs)
capabilities.update(options.to_capabilities())

driver = webdriver.Chrome('.\chromedriver.exe', options=options)

url = 'URL GOES HERE'

driver.get(url)

print("Navigating to", url)
driver.get(url)

# Define Text Boxes For Login
print('Logging into GoAnywhere Website')
username = driver.find_element_by_id('email')
password = driver.find_element_by_name('secret')

# Enter Username/Password
username.send_keys(user_id)
password.send_keys(user_password)
password.send_keys('\n')

# Wait for Page to load

....[这里的导航逻辑]....

# Click Upgrades
print("Selecting Upgrades")
time.sleep(1)
driver.find_element_by_xpath('//div[@id="accordionPanel"]/div[5]').click()

# CLick Upgrade Jar File
time.sleep(1)
print("Downloading upgrade jar to", download_dir)
driver.find_element_by_xpath('//a[@id="accordionPanel:j_id_3a:1:j_id_3j"]').click()

....[下载后处理文件的逻辑]....


【问题讨论】:

  • 当你点击这个时会发生什么:driver.find_element_by_xpath('//div[@id="accordionPanel"]/div[5]').click()?它会打开另一个页面吗?
  • 同一页面,只是浏览网站的 GUI。它们不像其他页面的 ahrefs。
  • 如果您无法访问您的网站,则很难解决此问题。我会玩导航逻辑,看看这是否会导致问题。您也许可以将该逻辑折叠到一个 xpath 调用中进行测试。我也总是把我的点击代码分开。
  • 您正在登录公司 GoAnywhere 帐户吗?
  • 是的,我正在自动下载升级 jar 文件。

标签: python selenium google-chrome selenium-webdriver


【解决方案1】:

2021 年 5 月 28 日更新


在进行更多测试后,我确定以下代码在未启用任何类型的 Chrome 浏览器策略的 Microsoft Windows 平台上完美运行。

Microsoft Windows 平台 处于企业 IT 控制 之下时,代码可能会失败Google 拥有允许企业 IT 设置 Chrome 策略的策略模板,这些策略可以覆盖此答案中的 selenium 代码。

例如,这是企业 IT 可以设置的一种政治策略,它将否定此答案中的 selenium 代码。

如果 SafeBrowsingProtectionLevel_StandardProtectionSafeBrowsingProtectionLevel_EnhancedProtection 已启用,Google Chrome 将就可能存在风险的网站、下载和扩展程序向您发出警告。

 CATEGORY !!SafeBrowsing_Category
        POLICY !!SafeBrowsingExtendedReportingEnabled_Policy
          #if version >= 4
            SUPPORTED !!SUPPORTED_WIN7
          #endif
          EXPLAIN !!SafeBrowsingExtendedReportingEnabled_Explain
          VALUENAME "SafeBrowsingExtendedReportingEnabled"
          VALUEON NUMERIC 1
          VALUEOFF NUMERIC 0
        END POLICY

        POLICY !!SafeBrowsingProtectionLevel_Policy
          #if version >= 4
            SUPPORTED !!SUPPORTED_WIN7
          #endif
          EXPLAIN !!SafeBrowsingProtectionLevel_Explain

          PART !!SafeBrowsingProtectionLevel_Part  DROPDOWNLIST
            VALUENAME "SafeBrowsingProtectionLevel"
            ITEMLIST
              NAME !!SafeBrowsingProtectionLevel_NoProtection_DropDown VALUE NUMERIC 0
              NAME !!SafeBrowsingProtectionLevel_StandardProtection_DropDown VALUE NUMERIC 1
              NAME !!SafeBrowsingProtectionLevel_EnhancedProtection_DropDown VALUE NUMERIC 2
            END ITEMLIST
          END PART
        END POLICY

我也在 Chrome 的源代码中注意到了这一点。这就是为什么在下载 .jar 文件时会抛出消息“这种类型的文件可能会损害您的计算机”

namespace download_util

static const struct Executables {
    const char* extension;
    DownloadDangerLevel level;
} g_executables[] = {

// Some files are dangerous on all platforms.

truncated...

  // Java.
{ "class", DANGEROUS },
{ "jar", DANGEROUS },
{ "jnlp", DANGEROUS },

truncated...

Jar 文件Google Chrome 认为是危险的。下面的措辞来自 Chrome 的 GitHub 存储库。

请注意,下面的文字是关于在 Chrome 浏览器的用户界面 (UI) 中显示警告消息的。

platform_settings.danger_level:(必需)控制在没有来自安全浏览 ping 的更好信号的情况下,UI 应如何处理文件。这适用于 ping_setting 为 SAMPLED_PING 或 NO_PING 的所有文件类型,以及安全浏览 ping 失败、禁用或返回 UNKNOWN 判断的下载。例外情况如下所示。

此处控制的警告是通用的“此文件可能会损坏您的计算机”。如果安全浏览判定为 UNCOMMON、POTENTIALLY_UNWANTED、DANGEROUS_HOST 或 DANGEROUS,则无论此设置如何,Chrome 都会显示更严重的警告。

此政策还影响如何处理子资源以“另存为...”下载完整的网页。如果任何子资源的文件类型被认为是 DANGEROUS 或 ALLOW_ON_USER_GESTURE,则文件名将更改为以 .download 结尾。这样做是为了防止文件被意外打开。

此政策还影响如何处理子资源以“另存为...”下载完整的网页。如果任何子资源的文件类型被认为是 DANGEROUS 或 ALLOW_ON_USER_GESTURE,则文件名将更改为以 .download 结尾。这样做是为了防止文件被意外打开。

  • NOT_DANGEROUS:即使下载是意外的,也可以安全下载和打开。不需要额外的警告。

  • 危险:始终警告用户此文件可能会损害他们的计算机。我们让他们继续或丢弃文件。如果安全浏览返回 SAFE 判断,我们仍会警告用户。

结论


这个问题的 OP 在 cmets 中说他使用的是公司 IT 控制的计算机。很可能在 OP 的系统上启用了 SafeBrowsingProtection。通过企业 IT 实施的这种额外级别的安全保护,此答案中的 selenium 代码无法抑制在 OP 的 Chrome 浏览器 UI 中显示的警告消息。

OP 表示,在无头模式下使用 selenium 和 Chrome 时,他能够绕过“这种类型的文件可能会损害您的计算机”消息。消息被抑制的原因是因为无头模式不使用 UI,因此不会引发警告消息。 Chrome 自己的文档/源代码验证此警告消息仅显示在 UI 中。参考:platform_settings.danger_level 上面。

2021 年 5 月 12 日原帖


下面的代码允许我单击 .jar 文件的 href 链接,而不会收到 “这种类型的文件会损害您的计算机” 消息。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

chrome_options = Options()
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("start-maximized")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-popup-blocking")

# disable the banner "Chrome is being controlled by automated test software"
chrome_options.add_experimental_option("useAutomationExtension", False)
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])


prefs = {
    'download.default_directory': 'download_directory',
    'download.prompt_for_download': False,
    'download.extensions_to_open': 'jar',
    'safebrowsing.enabled': True
}

capabilities = DesiredCapabilities().CHROME
chrome_options.add_experimental_option('prefs', prefs)
capabilities.update(chrome_options.to_capabilities())

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

# I used this site in my testing, because it had JAR files
url_main = 'http://www.jgoodies.com/downloads/demos/'

driver.get(url_main)


driver.implicitly_wait(20)

# download a jar file
download_jar_file = driver.find_element_by_xpath('//*[@id="post-70"]/div/table/tbody/tr[2]/td[5]/a')
download_jar_file.click()

偏好 download.extensions_to_openChrome 的 源代码中的此策略相关联。

"AutoOpenFileTypes" : {
    "os": ["win", "mac", "linux", "chromeos"],
    "policy_pref_mapping_tests": [
      {
        "policies": { "AutoOpenFileTypes": ["exe", ".txt", "pdf"] },
        "prefs": {
          "download.extensions_to_open_by_policy": {"value" : ["exe", "pdf"] }
        }
      }
    ]
  },
----------------------------------------
My system information
----------------------------------------
Platform:     macOS
Python:       3.8.0
Selenium:     3.141.0
Chromedriver: 90.0.4430.24
----------------------------------------

【讨论】:

  • 刚刚试了一下,我得到了相同的结果。文件下载正常,但在询问我是否要“保留”文件之后。
  • 您是按原样测试我的代码(哪个有效)还是将我的代码与您的代码集成?如果是后者,我需要看看你是如何集成代码的。
  • 是的,我唯一改变的是下载目录,我必须在网站上添加点击次数以及登录凭据,但这只是导航到下载所在的页面。
  • 我的代码按您对 jgoodies.com 网站的要求工作。您更新的代码与我发布的不符。
  • 更新的代码只是演示--headless。但我可以用你的解决方案发布另一个更新。
【解决方案2】:

尝试在您的 chrome 选项设置中添加 chrome_options.add_argument('--safebrowsing-disable-download-protection')

编辑:

等一下。你已经定义了options = webdriver.ChromeOptions()。尝试像这样设置参数?

options.add_argument('--disable-gpu')
options.add_argument('--disable-software-rasterizer')
options.add_argument('--safebrowsing-disable-download-protection')

【讨论】:

  • 遗憾的是这不起作用。文件下载后仍然收到相同的消息。
  • 您是否在 Chrome 中选择了选项"Protect you and your device from dangerous sites"?如果不是,我认为你也需要这样做。
  • 出现的浏览器窗口已设置为标准保护。是否有标志或选项可以将其变为无保护?
  • 它应该有标准的保护才能工作。好吧,我没有想法。我希望你或其他人能解决这个问题。
  • 不胜感激,希望有人能提供帮助。
猜你喜欢
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多