簡體   English   中英

Selenium 和無頭 chrome 通過 python 下載

[英]Selenium and headless chrome downloads via python

因此,通過無頭 chrome 與 selenium 下載文件的問題似乎仍然是一個問題,因為一個多月前在這里問過沒有答案。 但我不明白他們是如何實現 bug 線程中的 js 的。 有沒有我可以添加的選項或當前的修復程序? 位於此處的原始錯誤頁面截至今天 10/22/17 我所有的東西都是最新的

在蟒蛇中:

from selenium import webdriver


options = webdriver.ChromeOptions()

prefs = {"download.default_directory": "C:/Stuff", 
         "download.prompt_for_download": False,
         "download.directory_upgrade": True, 
         "plugins.always_open_pdf_externally": True
         }

options.add_experimental_option("prefs", prefs)
options.add_argument('headless')
driver = webdriver.Chrome(r'C:/Users/aaron/chromedriver.exe', chrome_options = options)

# test file to download which doesn't work
driver.get('http://ipv4.download.thinkbroadband.com/5MB.zip')

如果刪除無頭選項,這沒有問題。

我嘗試下載的實際文件是位於 .aspx URL 的 PDF。 我正在通過執行 .click() 下載它們,除了無頭版本之外,它效果很好。 hrefs 是 javascript do_postback 腳本。

為什么不找到錨點href,然后使用get請求下載文件。 這樣它將在無頭模式下工作並且速度會快得多。 我已經在 C# 中做到了。

def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024): 
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                #f.flush() commented by recommendation from J.F.Sebastian
    return local_filename

我相信現在 Chromium 支持此功能(如您鏈接到錯誤票證),由 chromedriver 團隊添加對該功能的支持。 有一個開放的車票 在這里,但它不會出現在目前具有較高的優先級。 請所有需要此功能的人給它 +1!

對於那些不在上面鏈接的鉻票上或尚未找到解決方案的人。 這對我有用。 Chrome 已更新到 v65,並且 chromedriver/selenium 都是截至 2018 年 4 月 16 日的最新版本。

    prefs = {'download.prompt_for_download': False,
             'download.directory_upgrade': True,
             'safebrowsing.enabled': False,
             'safebrowsing.disable_download_protection': True}

    
    options.add_argument('--headless')
    options.add_experimental_option('prefs', prefs)
    driver = webdriver.Chrome('chromedriver.exe', chrome_options=options)
    driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
    driver.desired_capabilities['browserName'] = 'ur mum'
    params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': r'C:\chickenbutt'}}
    driver.execute("send_command", params)

如果下載時遇到 Failed-file path too long 錯誤,請確保下載路徑沒有尾隨空格或斜杠\\或反斜杠。 路徑也必須僅使用反斜杠。 我不知道為什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM