首页 > 代码库 > Selenium - WebDriver

Selenium - WebDriver

$ pip install selenium
$ npm install selenium-webdriver

 

Example (python):

from selenium import webdriverfrom selenium.common.exceptions import TimeoutExceptionfrom selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0# Create a new instance of the Firefox driverdriver = webdriver.Firefox()# go to the google home pagedriver.get("http://www.google.com")# the page is ajaxy so the title is originally this:print driver.title# find the element that‘s name attribute is q (the google search box)inputElement = driver.find_element_by_name("q")# type in the searchinputElement.send_keys("cheese!")# submit the form (although google automatically searches now without submitting)inputElement.submit()try:    # we have to wait for the page to refresh, the last thing that seems to be updated is the title    WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))    # You should see "cheese! - Google Search"    print driver.titlefinally:    driver.quit()

Example(JavaScript):

var driver = new webdriver.Builder().build();driver.get(‘http://www.google.com‘);var element = driver.findElement(webdriver.By.name(‘q‘));element.sendKeys(‘Cheese!‘);element.submit();driver.getTitle().then(function(title) {  console.log(‘Page title is: ‘ + title);});driver.wait(function() {  return driver.getTitle().then(function(title) {    return title.toLowerCase().lastIndexOf(‘cheese!‘, 0) === 0;  });}, 3000);driver.getTitle().then(function(title) {  console.log(‘Page title is: ‘ + title);});driver.quit();

 

Selenium-WebDriver API Commands and Operations

1. Fetching a Page

# Pythondriver.get("http://www.google.com")
// JavaScriptdriver.get(‘http://www.google.com‘);

2. Locating UI Elements (WebElements)

  • By ID

  example for element:

<div id="coolestWidgetEvah">...</div>
# Pythonelement = driver.find_element_by_id("coolestWidgetEvah")orfrom selenium.webdriver.common.by import Byelement = driver.find_element(by=By.ID, value=http://www.mamicode.com/"coolestWidgetEvah")
// JavaScriptvar element = driver.findElement(By.id(‘coolestWidgetEvah‘));
  • By Class Name

  example for elements:

<div class="cheese"><span>Cheddar</span></div>
<
div class="cheese"><span>Gouda</span></div>
# Pythoncheeses = driver.find_elements_by_class_name("cheese")orfrom selenium.webdriver.common.by import Bycheeses = driver.find_elements(By.CLASS_NAME, "cheese")
// JavaScriptdriver.findElements(By.className("cheese")).then(cheeses => console.log(cheeses.length));
  • By Tag Name

  example for element:

<iframe src="..."></iframe>
# Pythonframe = driver.find_element_by_tag_name("iframe")orfrom selenium.webdriver.common.by import Byframe = driver.find_element(By.TAG_NAME, "iframe")
// JavaScriptvar frame = driver.findElement(By.tagName(‘iframe‘));
  • By Name

  example for element:

<input name="cheese" type="text"/>
# Pythoncheese = driver.find_element_by_name("cheese")#orfrom selenium.webdriver.common.by import Bycheese = driver.find_element(By.NAME, "cheese")
// JavaScriptvar cheese = driver.findElement(By.name(‘cheese‘));
  • By Link Text

  example for element:

<a href="http://www.google.com/search?q=cheese">cheese</a>
# Pythoncheese = driver.find_element_by_link_text("cheese")#orfrom selenium.webdriver.common.by import Bycheese = driver.find_element(By.LINK_TEXT, "cheese")
// JavaScriptvar cheese = driver.findElement(By.linkText(‘cheese‘));
  • By Partial Link Text

  example for element:

<a href="http://www.google.com/search?q=cheese">search for cheese</a>
# Pythoncheese = driver.find_element_by_partial_link_text("cheese")#orfrom selenium.webdriver.common.by import Bycheese = driver.find_element(By.PARTIAL_LINK_TEXT, "cheese")
// JavaScriptvar cheese = driver.findElement(By.partialLinkText(‘cheese‘));
  • By CSS

  example for element:

<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>
# Pythoncheese = driver.find_element_by_css_selector("#food span.dairy.aged")#orfrom selenium.webdriver.common.by import Bycheese = driver.find_element(By.CSS_SELECTOR, "#food span.dairy.aged")
// JavaScriptvar cheese = driver.findElement(By.css(‘#food span.dairy.aged‘));
  • By XPath

DriverTag and Attribute NameAttribute ValuesNative XPath Support
HtmlUnit DriverLower-casedAs they appear in the HTMLYes
Internet Explorer DriverLower-casedAs they appear in the HTMLNo
Firefox DriverCase insensitiveAs they appear in the HTMLYes

  example for elements:

<input type="text" name="example" /><INPUT type="text" name="other" />
# Pythoninputs = driver.find_elements_by_xpath("//input")#orfrom selenium.webdriver.common.by import Byinputs = driver.find_elements(By.XPATH, "//input")
// JavaScriptdriver.findElements(By.xpath("//input")).then(cheeses => console.log(cheeses.length));

  The following number of matches will be found:

XPath expressionHtmlUnit DriverFirefox DriverInternet Explorer Driver
//input1 (“example”)22
//INPUT020
  • Using JavaScript

  You can execute arbitrary javascript to find an element and as long as you return a DOM Element, it will be automatically converted to a WebElement object.

  Simple example on a page that has jQuery loaded:

# Pythonelement = driver.execute_script("return $(‘.cheese‘)[0]")

  Finding all the input elements for every label on a page:

# Pythonlabels = driver.find_elements_by_tag_name("label")inputs = driver.execute_script(    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +    "inputs.push(document.getElementById(labels[i].getAttribute(‘for‘))); } return inputs;", labels)
  • Get Text Value

# Pythonelement = driver.find_element_by_id("element_id")element.text
// JavaScriptvar element = driver.findElement(By.id(‘elementID‘));element.getText().then(text => console.log(`Text is `));
  • User Input - Filling In Forms

# Python# This will find the first “SELECT” element on the page, and cycle through each of it’s OPTIONs in turn, printing out their values, and selecting each in turn.select = driver.find_element_by_tag_name("select")allOptions = select.find_elements_by_tag_name("option")for option in allOptions:    print "Value is: " + option.get_attribute("value")    option.click()

  As you can see, this isn’t the most efficient way of dealing with SELECT elements . WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these:

# Python# available since 2.12from selenium.webdriver.support.ui import Selectselect = Select(driver.find_element_by_name(name))select.select_by_index(index)select.select_by_visible_text("text")select.select_by_value(value)

  WebDriver also provides features for deselecting all the selected options:

# Pythonselect = Select(driver.find_element_by_id(id))select.deselect_all()
# To get all selected optionsselect = Select(driver.find_element_by_xpath("xpath"))all_selected_options = select.all_selected_options# To get all optionsoptions = select.options
# Pythondriver.find_element_by_id("submit").click()
// JavaScriptdriver.findElement(By.id(‘submit‘).click();
# Pythonelement.submit()
// JavaScriptelement.submit();
  • Move between Windows and Frames

# Pythondriver.switch_to.window("windowName")
// JavaScriptdriver.switchTo().window(‘windowName‘);

  All calls to driver will now be interpreted as being directed to the particular window. But how do you know the window’s name? Take a look at the javascript or link that opened it:

<a href="somewhere.html" target="windowName">Click here to open a new window</a>

Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:

# Pythonfor handle in driver.window_handles:    driver.switch_to.window(handle)
# Pythondriver.switch_to.frame("frameName")
// JavaScriptdriver.switchTo().frame(‘frameName‘);
  • Pop Dialog

# Pythonalert = driver.switch_to.alert# usage: alert.dismiss(), etc.
// JavaScriptvar alert = driver.switchTo().alert();alert.accept();
  • Navigation: History and Location

# Pythondriver.get("http://www.example.com")  # python doesn‘t have driver.navigate
// JavaScriptdriver.navigate().to(‘http://www.example.com‘);
# Pythondriver.forward()driver.back()
// JavaScriptdriver.navigate().forward();driver.navigate().back();
  • Cookie

# Python# Go to the correct domaindriver.get("http://www.example.com")# Now set the cookie. Here‘s one for the entire domain# the cookie name here is ‘key‘ and its value is ‘value‘driver.add_cookie({name:key, value:value, path:/})# additional keys that can be passed in are:# ‘domain‘ -> String,# ‘secure‘ -> Boolean,# ‘expiry‘ -> Milliseconds since the Epoch it should expire.# And now output all the available cookies for the current URLfor cookie in driver.get_cookies():    print "%s -> %s" % (cookie[name], cookie[value])# You can delete cookies in 2 ways# By namedriver.delete_cookie("CookieName")# Or all of themdriver.delete_all_cookies()
// JavaScript// Go to the correct domaindriver.get(‘http://www.example.com‘);// Now set the basic cookie. Here‘s one for the entire domain// the cookie name here is ‘key‘ and its value is ‘value‘driver.manage().addCookie({name: ‘cookie-1‘, value: ‘cookieValue‘});// And now output all the available cookies for the current URLdriver.manage().getCookies().then( (loadedCookies) =>{    for (let cookie in loadedCookies) {    console.log(‘printing Cookies loaded : ‘+cookie);    }    });// You can delete cookies in 2 ways// By namedriver.manage().deleteCookie(‘cookie-1‘);// Or all of themdriver.manage().deleteAllCookies();
  • Change the User Agent

# Pythonprofile = webdriver.FirefoxProfile()profile.set_preference("general.useragent.override", "some UA string")driver = webdriver.Firefox(profile)
  • Drag and Drop

# Pythonfrom selenium.webdriver.common.action_chains import ActionChainselement = driver.find_element_by_name("source")target =  driver.find_element_by_name("target")ActionChains(driver).drag_and_drop(element, target).perform()

 3. Selenium-WebDriver‘s Driver

  • HtmlUnit Driver

# Pythondriver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNIT.copy())
# Python# If you can’t wait, enabling JavaScript support is very easy:driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.HTMLUNITWITHJS)# This will cause the HtmlUnit Driver to emulate Firefox 3.6’s JavaScript handling by default.
  • Firefox driver

# Pythondriver = webdriver.Firefox()
# Python# Modify Firefox Profileprofile = webdriver.FirefoxProfile()profile.native_events_enabled = Truedriver = webdriver.Firefox(profile)
  • Internet Explorer Driver

# Pythondriver = webdriver.Ie()
  • Chrome Driver

# Pythondriver = webdriver.Chrome()

 

Selenium - WebDriver