Creating a headless Chrome instance in Python

后端 未结 5 694
陌清茗
陌清茗 2020-12-23 18:09

This question describes my conclusion after researching available options for creating a headless Chrome instance in Python and asks for confirmation or resources that descr

5条回答
  •  既然无缘
    2020-12-23 18:34

    I use this to get the driver:

    def get_browser(storage_dir, headless=False):
        """
        Get the browser (a "driver").
    
        Parameters
        ----------
        storage_dir : str
        headless : bool
    
        Results
        -------
        browser : selenium webdriver object
        """
        # find the path with 'which chromedriver'
        path_to_chromedriver = '/usr/local/bin/chromedriver'
    
        from selenium.webdriver.chrome.options import Options
        chrome_options = Options()
        if headless:
            chrome_options.add_argument("--headless")
        chrome_options.add_experimental_option('prefs', {
            "plugins.plugins_list": [{"enabled": False,
                                      "name": "Chrome PDF Viewer"}],
            "download": {
                "prompt_for_download": False,
                "default_directory": storage_dir,
                "directory_upgrade": False,
                "open_pdf_in_system_reader": False
            }
        })
    
        browser = webdriver.Chrome(path_to_chromedriver,
                                   chrome_options=chrome_options)
        return browser
    

    By switching the headless parameter you can either watch it or not.

提交回复
热议问题