Chromedriver options selenium python

Capabilities & ChromeOptions

Capabilities are options that you can use to customize and configure a ChromeDriver session. This page documents all ChromeDriver supported capabilities and how to use them.

The WebDriver language APIs provides ways to pass capabilities to ChromeDriver. The exact mechanism differs by the language, but most languages use one or both of the following mechanisms:

  1. Use the ChromeOptions class. This is supported by Java, Python, etc.
  2. Use the DesiredCapabilities class. This is supported by Python, Ruby, etc. While it is also available in Java, its usage in Java is deprecated.

You can create an instance of ChromeOptions , which has convenient methods for setting ChromeDriver-specific capabilities. You can then pass the ChromeOptions object into the ChromeDriver constructor:

ChromeOptions options = new ChromeOptions();

options.addExtensions( new File(» /path/to/extension.crx «));

ChromeDriver driver = new ChromeDriver(options);

Since Selenium version 3.6.0, the ChromeOptions class in Java also implements the Capabilities interface, allowing you to specify other WebDriver capabilities not specific to ChromeDriver.

ChromeOptions options = new ChromeOptions();

// Add the WebDriver proxy capability.

Proxy proxy = new Proxy();

options.setCapability(» proxy «, proxy);

// Add a ChromeDriver-specific capability.

options.addExtensions( new File(» /path/to/extension.crx «));

ChromeDriver driver = new ChromeDriver(options);

To use DesiredCapabilities , you need to know the name of the capability and the type of value it takes. See the full list further below.

driver = Selenium::WebDriver. for :chrome, desired_capabilities: caps

Use custom profile (also called user data directory)

By default, ChromeDriver will create a new temporary profile for each session. At times you may want to set special preferences or just use a custom profile altogether. If the former, you can use the ‘chrome.prefs’ capability (described later below) to specify preferences that will be applied after Chrome starts. If the latter, you can use the user-data-dir Chrome command-line switch to tell Chrome which profile to use:

Читайте также:  Где практиковаться в программировании python

ChromeOptions options = new ChromeOptions();

You can create your own custom profile by just running Chrome (on the command-line or through ChromeDriver) with the user-data-dir switch set to some new directory. If the path doesn’t exist, Chrome will create a new profile in the specified location. You can then modify the profile settings as desired, and ChromeDriver can use the profile in the future. Open chrome://version in the browser to see what profile Chrome is using.

Start Chrome maximized

ChromeOptions options = new ChromeOptions();

Using a Chrome executable in a non-standard location

ChromeOptions options = new ChromeOptions();

Block pop-up windows

By default, ChromeDriver configures Chrome to allow pop-up windows. If you want to block pop-ups (i.e., restore the normal Chrome behavior when it is not controlled by ChromeDriver), do the following:

ChromeOptions options = new ChromeOptions();

Set download directory

The following code can be used to configure Chrome to download files to a specific directory. However, there are several caveats to be aware of:

  • Chrome disallows using certain directories for download. In particular, you cannot use the desktop folder as the download directory. On Linux, you also cannot use the home directory for download. Since the exact list of forbidden directories is subject to change, it is recommended that you use a directory that has no special meaning to the system.
  • ChromeDriver does not automatically wait for download to complete. If you call driver.quit() too soon, Chrome might terminate before the download has finished.
  • Relative paths do not always work. For best result, use full path instead.
  • On Windows, Use «\» as path separators. Using «/» is not reliable on Windows.

ChromeOptions options = new ChromeOptions();

Map prefs = new HashMap();

prefs.put(» download.default_directory «, » /directory/path «);

options.setExperimentalOption(» prefs «, prefs);

Please see Selenium documentation and W3C WebDriver standard for standard capabilities accepted by ChromeDriver. Here we only list Chrome-specific capabilities.

Most Chrome-specific capabilities are exposed through the ChromeOptions object. In some languages, this is implemented by the ChromeOptions class. In other languages, they are stored under the goog:chromeOptions dictionary in desired capabilities.

Читайте также:  Return result query php

Источник

How to use the selenium.webdriver.ChromeOptions function in selenium

To help you get started, we’ve selected a few selenium examples, based on popular ways it is used in public projects.

Secure your code as it’s written. Use Snyk Code to scan source code in minutes — no build needed — and fix issues immediately.

def setup_browser(): if use_firefox: world.browser = MyFirefox() world.browser.set_window_size(450, 1200) world.browser.set_window_position(0, 0) #world.browser.maximize_window() elif use_phantomjs: world.browser = MyPhantomJS() elif use_headless_chrome: options = ChromeOptions() options.add_argument("--window-size=1005,9999") options.add_argument("--headless"); world.browser = MyChrome(executable_path=os.path.join('..', '..', 'chromedriver'), chrome_options=options) else: options = ChromeOptions() options.add_argument("--start-maximized"); world.browser = MyChrome(executable_path=os.path.join('..', '..', 'chromedriver'), chrome_options=options) world.da_path = default_path world.wait_seconds = default_wait_seconds
:param browser_name: browser name in lowercase :type browser_name: str :param headless: run browser without gui :type headless: bool :return: capabilities for specific browser :rtype: dict """ if self.is_appium_based: return options = None if 'firefox' == browser_name: options = FirefoxOptions() elif 'chrome' == browser_name: options = ChromeOptions() options.add_argument('disable-infobars') if options and headless: options.headless = True # huck for preventing overwriting 'platform' value in desired_capabilities by chrome options browser_caps = options.to_capabilities() if options else <> browser_name, browser_version = [b for b in self.browsers if browser_name.lower() == b[0].lower()][0] browser_caps.update() if isinstance(self.extra, dict): browser_caps.update(self.extra) return browser_caps 
def __init__(self): url = 'https://login.taobao.com/member/login.jhtml' self.url = url options = webdriver.ChromeOptions() options.add_experimental_option("prefs", "profile.managed_default_content_settings.images": 2>) # 不加载图片,加快访问速度 options.add_experimental_option('excludeSwitches', ['enable-automation']) # 此步骤很重要,设置为开发者模式,防止被各大网站识别出来使用了Selenium self.browser = webdriver.Chrome(executable_path=chromedriver_path, options=options) self.wait = WebDriverWait(self.browser, 10) #超时时长为10s
def start_browser(self): # Initialize chromedriver and configure its options options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--log-level=3') options.add_argument('--disable-gpu') options.add_argument('--disable-infobars') options.add_argument("--window-size=1600,2020") if self.DRIVER_PATH: # search for chromedriver in assets self.driver = webdriver.Chrome(executable_path=self.DRIVER_PATH, options=options) else: # search for chromedriver in PATH try: self.driver = webdriver.Chrome(options=options) except ConnectionResetError as e: self.logger.error('Failed to start webdriver: %s', str(e), extra='label': 'error'>) # sys.exit(1) except WebDriverException: self.logger.error('Chromedriver needs to be in assets directory or in PATH', extra='label': 'error'>)
def setup_chrome_browser(self): ''' This function allows for setting up a chrome driver for use with Selenium. It expects a path to a chromedriver, available for download on this link: https://chromedriver.chromium.org/home ''' if os.name == 'posix': chromedriver = '/chromedriver' elif os.name == 'nt': chromedriver = '/chromedriver.exe' options = webdriver.ChromeOptions() prefs = "profile.default_content_setting_values.notifications" : 2> options.add_experimental_option("prefs", prefs) options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_argument("--headless") path = os.path.dirname(os.path.abspath(__file__)) self.driver = webdriver.Chrome(executable_path = path + chromedriver, options=options)
def _get_Chrome(self): try: chrome_ops = webdriver.ChromeOptions() if self.proxy: chrome_ops = webdriver.ChromeOptions() chrome_ops.add_argument( '--proxy-server=<>://<>:<>'.format( self.proxy.proto, self.proxy.host, self.proxy.port ) ) self.webdriver = webdriver.Chrome( executable_path=self.config['executable_path'], chrome_options=chrome_ops ) if self.config.get('chrome_headless') is True: chrome_ops.add_argument('--headless')
ride = hsRides[int(ride)-1] elif park == "4": print("Avatar Flight of Passage: 1 | Na'vi River Journey: 2 | DINOSAUR: 3 | Everest: 4 | Festival of the Lion King: 5 | Finding Nemo - The Musical: 6 | It's Tough to be a Bug!: 7 | Kali River Rapids: 8 | Kilimanjaro Safaris: 9 | Meet Favorite Disney Pals: 10 | Primeval Whirl: 11 | Rivers of Light: 12") print("") ride = input("Choose a Ride: ") while ride not in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]: ride = input("Choose a Ride: ") ride = akRides[int(ride)-1] print("") time = input("Select A Time: ") timeZone = input("AM or PM: ") #user input is over and webdriver is starting below options = webdriver.ChromeOptions() options.add_argument("--start-maximized") #change path to your path of chromedriver! chrome_path = r"/usr/lib/chromium-browser/chromedriver" driver = webdriver.Chrome(chrome_path, chrome_options=options) driver.get("https://disneyworld.disney.go.com/fastpass-plus/") #all the while loops like this are so the website clicks a button right away while x == False: try: #clicks Get Started button driver.find_element_by_xpath("""//*[@id="fastPasslandingPage"]/div[3]/div[1]/div/div/div/div""").click() x = True except: x = False x = False
if __name__ == '__main__': # chromedriver驱动文件的位置,可输入绝对路径或者相对路径,./表示当前目录下 # './chromedriver_win32.exe'表示当前目录下的chromedriver_win32.exe文件 # 不同系统和不同chrome版本需要下载不同的chromedriver,请下载合适自己的版本 # chromedriver下载地址http://chromedriver.chromium.org/downloads # 默认的chromedriver支持的Chrome版本为74 # chromedriver_path = './chromedriver_win32_74.0.3729.6.exe' chromedriver_path = './chromedriver_mac_74.0.3729.6' option = webdriver.ChromeOptions() # 屏蔽chrome的提示 option.add_argument('disable-infobars') # 静默自动打印为高清PDF文件,并存储到os.getcwd()目录,也就是当前目录 appState = < # 添加保存为pdf选项 "recentDestinations": [ < "id": "Save as PDF", "origin": "local", "account":"" > ], # 选择保存为pdf选项 "selectedDestinationId": "Save as PDF", # 版本2 "version": 2,
def get_browser(): chromedriver = os.path.join(needl.args.datadir, 'chromedriver') if not os.path.exists(chromedriver): raise FileNotFoundError("Could not find chromedriver executable at %s. Download it for your platform at https://chromedriver.storage.googleapis.com/index.html?path=2.33/", chromedriver) chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('headless') chrome_options.add_argument('window-size=1024x3000') chrome_options.add_argument("user-agent=" + get_line(os.path.join(needl.args.datadir, 'user-agents.txt'))) return webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_options)
def gen_chrome_options(): chrome_options = ChromeOptions() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1366x768") chrome_options.add_argument("--disable-application-cache") chrome_options.add_argument("--disable-infobars") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--hide-scrollbars") chrome_options.add_argument("--enable-logging") chrome_options.add_argument("--log-level=0") chrome_options.add_argument("--single-process") chrome_options.add_argument("--ignore-certificate-errors") chrome_options.add_argument("--homedir=/tmp") return chrome_options

Источник

Оцените статью