Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Ruby Bindings

Titus edited this pageOct 25, 2021 ·15 revisions

This page is outdated and unofficial, check for the latest information in theSelenium Documentation

Introduction

The Ruby bindings for Selenium/WebDriver are available as theselenium-webdriver gem. The web page explains how to install the selenium-webdriver gem. If you're looking for a slightly higher level API built on the same technology, you may want to check outwatir orcapybara.

The bindings support Ruby 2.1 through 2.4.

API Example

require"selenium-webdriver"driver=Selenium::WebDriver.for:firefoxdriver.navigate.to"http://google.com"element=driver.find_element(name:'q')element.send_keys"Hello WebDriver!"element.submitputsdriver.titledriver.quit

Driver examples:

# execute arbitrary javascriptputsdriver.execute_script("return window.location.pathname")# pass elements between Ruby and JavaScriptelement=driver.execute_script("return document.body")driver.execute_script("return arguments[0].tagName",element)#=> "BODY"# wait for a specific element to show upwait=Selenium::WebDriver::Wait.new(timeout:10)# secondswait.until{driver.find_element(id:"foo")}# switch to a framedriver.switch_to.frame"some-frame"# iddriver.switch_to.framedriver.find_element(id:'some-frame')# frame element# switch back to the main documentdriver.switch_to.default_content# repositioning and resizing browser window:driver.manage.window.move_to(300,400)driver.manage.window.resize_to(500,800)driver.manage.window.maximize

Element examples:

# get an attributeclass_name=element.attribute("class")# is the element visible on the page?element.displayed?# click the elementelement.click# get the element locationelement.location# scroll the element into view, then return its locationelement.location_once_scrolled_into_view# get the width and height of an elementelement.size# press space on an element - see Selenium::WebDriver::Keys for possible valueselement.send_keys:space# get the text of an elementelement.text

Advanced user interactions (seeActionBuilder):

driver.action.key_down(:shift).click(element).double_click(second_element).key_up(:shift).drag_and_drop(element,third_element).perform

IE

Make sure thatInternet OptionsSecurity has the sameProtected Mode setting (on or off, it doesn't matter as long as it is the same value) for all zones.

Chrome

Command line switches

For a list of switches, seethis list.

options=Selenium::WebDriver::Chrome::Options.newoptions.add_argument('--ignore-certificate-errors')options.add_argument('--disable-popup-blocking')options.add_argument('--disable-translate')driver=Selenium::WebDriver.for:chrome,options:options

Tweaking profile preferences

prefs={prompt_for_download:false,default_directory:"/path/to/dir"}options=Selenium::WebDriver::Chrome::Options.newoptions.add_preference(:download,prefs)driver=Selenium::WebDriver.for:chrome,options:options

SeeChromeDriver documentation.

Remote

The RemoteWebDriver makes it easy to control a browser running on another machine. Download the SeleniumStandalone Server (fromDownloads) and launch:

java -jar selenium-server-standalone.jar

Then connect to it from Ruby

driver=Selenium::WebDriver.for:remote

By default, this connects to the server running on localhost:4444 and opens Chrome. To connect to another machine, use the:url option:

driver=Selenium::WebDriver.for:remote,url:"http://myserver:4444/wd/hub"

To launch another browser with the default capabilities, use the :desired_capabilities option:

driver=Selenium::WebDriver.for:remote,desired_capabilities::firefox

You can also pass an instance ofSelenium::WebDriver::Remote::Capabilities, e.g.:

caps=Selenium::WebDriver::Remote::Capabilities.internet_explorer(native_events:false)driver=Selenium::WebDriver.for:remote,desired_capabilities:caps

You can change arbitrary capabilities:

caps=Selenium::WebDriver::Remote::Capabilities.internet_explorercaps['enablePersistentHover']=falsedriver=Selenium::WebDriver.for:remote,desired_capabilities:caps

You may want to set the proxy settings of the remote browser (this currently only works for Firefox):

caps=Selenium::WebDriver::Remote::Capabilities.firefox(proxy:Selenium::WebDriver::Proxy.new(http:"myproxyaddress:8080"))driver=Selenium::WebDriver.for:remote,desired_capabilities:caps

Or if you have a proxy in front of the remote server:

client=Selenium::WebDriver::Remote::Http::Default.newclient.proxy=Selenium::Proxy.new(http:"proxy.org:8080")driver=Selenium::WebDriver.for:remote,http_client:client

SeeProxy documentation for more options.

For the remote Firefox driver you can configure the profile, see the sectionTweaking Firefox preferences.

Firefox

Ruby currently includes support for Legacy FirefoxDriver (used in Firefox versions < 48), and the newgeckodriver. As of Selenium 3.x, Geckodriver is the default implementation. If you want to use the Legacy Driver with an older version of Firefox you can do:

capabilities=Selenium::WebDriver::Remote::Capabilities.firefox(marionette:false)Selenium::WebDriver.for:firefox,desired_capabilities:capabilities

Both implementations allow you configure the profile used. The examples below, however, are for GeckoDriver.

Adding an extension

profile=Selenium::WebDriver::Firefox::Profile.newprofile.add_extension("/path/to/extension.xpi")options=Selenium::WebDriver::Firefox::Options.newoptions.profile=profiledriver=Selenium::WebDriver.for:firefox,options:options

Using an existing profile

You can use an existing profile as a template for the WebDriver profile by passing the profile name (seefirefox -ProfileManager to set up custom profiles.)

options=Selenium::WebDriver::Firefox::Options.newoptions.profile="my-existing-profile"driver=Selenium::WebDriver.for:firefox,options:options

If you want to use your default profile, passprofile = "default"

You can also get a Profile instance for an existing profile and tweak its preferences. This does not modify the existing profile, only the one used by WebDriver.

default_profile=Selenium::WebDriver::Firefox::Profile.from_name"default"default_profile.assume_untrusted_certificate_issuer=falseoptions=Selenium::WebDriver::Firefox::Options.new(profile:default_profile)driver=Selenium::WebDriver.for:firefox,options:options

Tweaking Firefox preferences

Use a proxy:

profile=Selenium::WebDriver::Firefox::Profile.newproxy=Selenium::WebDriver::Proxy.new(http:"proxy.org:8080")profile.proxy=proxyoptions=Selenium::WebDriver::Firefox::Options.new(profile:profile)driver=Selenium::WebDriver.for:firefox,options:options

Automatically download files to a given folder:

profile=Selenium::WebDriver::Firefox::Profile.newprofile['browser.download.dir']="/tmp/webdriver-downloads"profile['browser.download.folderList']=2profile['browser.helperApps.neverAsk.saveToDisk']="application/pdf"profile['pdfjs.disabled']=trueoptions=Selenium::WebDriver::Firefox::Options.new(profile:profile)driver=Selenium::WebDriver.for:firefox,options:options

If you are using the remote driver you can still configure the Firefox profile:

profile=Selenium::WebDriver::Firefox::Profile.newprofile['foo.bar']=truecapabilities=Selenium::WebDriver::Remote::Capabilities.firefox(firefox_profile:profile)driver=Selenium::WebDriver.for:remote,desired_capabilities:capabilities

For a list of possible preferences, seethis page.

Custom Firefox path

If your Firefox executable is in a non-standard location:

options=Selenium::WebDriver::Firefox::Options.newoptions.binary="/path/to/firefox"driver=Selenium::WebDriver.for:firefox,options:options

SSL Certificates

The Legacy Firefox driver ignores invalid SSL certificates by default. If this is not the behavior you want, you can do:

profile=Selenium::WebDriver::Firefox::Profile.newprofile.secure_ssl=truedriver=Selenium::WebDriver.for:firefox,profile:profile

geckodriver will not implicitly trust untrusted or self-signed TLS certificates on navigation. To override this you can do:

capabilities=Selenium::WebDriver::Remote::Capabilities.firefox(accept_insecure_certs:true)driver=Selenium::WebDriver.for:firefox,desired_capabilities:capabilities

Safari

As of 3.0, the only supported safari driver is the onemaintained by Apple. It requires Safari 10 or greater; support for earlier versions of Safari has been removed.

driver=Selenium::WebDriver.for:safaridriver.navigate.to"http://apple.com"

Technology Preview

The latest code for the Safari Driver is bundled with the Safari Technology Preview. To use it:

Selenium::WebDriver::Safari.driver_path="/Applications/Safari\Technology\Preview.app/Contents/MacOS/safaridriver"driver=Selenium::WebDriver.for:safari

Timeouts

Implicit waits

WebDriver lets you configure implicit waits, so that a call to#find_element will wait for a specified amount of time before raising aNoSuchElementError:

driver=Selenium::WebDriver.for:firefoxdriver.manage.timeouts.implicit_wait=3# seconds

Explicit waits

Use the Wait class to explicitly wait for some condition:

wait=Selenium::WebDriver::Wait.new(timeout:3)wait.until{driver.find_element(id:"cheese").displayed?}

Internal timeouts

Internally, WebDriver uses HTTP to communicate with a lot of the drivers (the JsonWireProtocol). By default,Net::HTTP from Ruby's standard library is used, which has a default timeout of 60 seconds. If you call e.g.Driver#get,Driver#click on a page that takes more than 60 seconds to load, you'll see aTimeout::Error raised fromNet::HTTP. You can configure this timeout (before launching a browser) by doing:

client=Selenium::WebDriver::Remote::Http::Default.newclient.read_timeout=120# secondsdriver=Selenium::WebDriver.for:remote,http_client:client

JavaScript dialogs

You can use WebDriver to handle Javascriptalert(),prompt() andconfirm() dialogs.The API for all three is the same.

require"selenium-webdriver"driver=Selenium::WebDriver.for:firefoxdriver.navigate.to"http://mysite.com/page_with_alert.html"driver.find_element(name:'element_with_alert_javascript').clicka=driver.switch_to.alertifa.text =='A value you are looking for'a.dismisselsea.acceptend

Using Curb or your own HTTP client

For internal HTTP communication,Net::HTTP is used by default. If you e.g. have theCurb gem installed, you can switch to it by doing:

require'selenium/webdriver/remote/http/curb'client=Selenium::WebDriver::Remote::Http::Curb.newdriver=Selenium::WebDriver.for:firefox,http_client:client

Using persistent HTTP connections

If you have thenet-http-persistent gem installed, you can use it to get keep-alive connections. This will significantly reduce the ephemeral ports usage of WebDriver, which is useful insome contexts. Keep-alive connections are also supported in ChromeDriver.

require'selenium/webdriver/remote/http/persistent'client=Selenium::WebDriver::Remote::Http::Persistent.newdriver=Selenium::WebDriver.for:chrome,http_client:client

Logging

There is built-in logger available, by default it prints only warning messages. If you want to enable more verbose logging, add this to your code:

Selenium::WebDriver.logger.level=:info

If you want full logging enabled:

Selenium::WebDriver.logger.level=:debug

By default, logger prints messages to standard output, but you can also write to a file:

Selenium::WebDriver.logger.output='selenium.log'

Notice for Users

This wiki is not where you want to be!Visit the Wiki Home for more useful links

For Developers and Contributors

Getting Involved
Triaging Issues
Releasing Selenium

Binding Specific Information

Ruby Development
Python Bindings
Ruby Bindings
WebDriverJs

Being Processed

This content is being evaluated for where it belongs

Architectural Overview
Automation Atoms
HtmlUnitDriver
Lift Style API
LoadableComponent
Logging
PageFactory
RemoteWebDriver
Xpath In WebDriver

Archived

Moved toOfficial Documentation

Bot Style Tests
Buck
Continuous Integration
Crazy Fun Build
Design Patterns
Desired Capabilities
Developer Tips
Domain Driven Design
Firefox Driver
Firefox Driver Internals
Focus Stealing On Linux
Frequently Asked Questions
Google Summer Of Code
Grid Platforms
History
Internet Explorer Driver
InternetExplorerDriver Internals
Next Steps
PageObjects
RemoteWebDriverServer
Roadmap
Scaling WebDriver
SeIDE Release Notes
Selenium Emulation
Selenium Grid 4
Selenium Help
Shipping Selenium 3
The Team
TLC Meetings
Untrusted SSL Certificates
WebDriver For Mobile Browsers
Writing New Drivers

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp