Selenium加--headless无界面下无法抓取图片或者其他文件的解决

宰父疏珂
2023-12-01

Selenium加–headless无界面下无法抓取图片或者其他文件的解决

  • 贴上代码

    url = '你的url'
    def enable_download_in_headless_chrome(browser, download_dir):
        #add missing support for chrome "send_command"  to selenium webdriver
        browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
    
        params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
        browser.execute("send_command", params)
    
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36")
    options.add_argument('--window-size=1280,1024')
    
    # options.add_experimental_option("prefs", {
    #   "download.default_directory":DIR_NAME,
    # })
    
    
    driver = webdriver.Chrome(executable_path='D:/webdriver/chromedriver',chrome_options=options)
    
    driver.set_window_size(1280, 720) 
    DIR_NAME ='E:/test_my/'
    
    enable_download_in_headless_chrome(driver, DIR_NAME)
    URL = url
    # print(URL)
    # print ("loading url")
    driver.get(URL)
    time.sleep(3)
    cookie_list = driver.get_cookies()
    cookie_list
    
 类似资料: