Selenium-getting Started

Source: Internet
Author: User
Tags selenium python

1.1. Simple Usage

If you had installed Selenium python bindings, you can start using it from Python like this.

FromSeleniumImportWebdriverFromSelenium.webdriver.common.keysImportKeysDriver=Webdriver.Firefox()Driver.Get("Http://www.python.org")Assert"Python"Inchdriver. Titleelem = driver. Find_element_by_name ( "Q" ) elemsend_keys ( "Pycon" ) elem send_keys (keys. Return) assert  "No results found." not in driver. Page_sourcedriver. Close ()               

The above script can be saved to a file (eg:- python_org_search.py), then it can is run like this:

Python python_org_search.py

The python which you is running should has the Selenium module installed.

1.2. Walk through of the example

The selenium.webdriver module provides all the Webdriver implementations. Currently supported Webdriver implementations is Firefox, Chrome, Ie and Remote. The keys class provide keys in the keyboard like RETURN, F1, ALT etc.

WebdriverKeys

Next, the instance of Firefox Webdriver is created.

Webdriver.  Firefox()  

The driver.get method would navigate to a page given by the URL. Webdriver'll wait until the page has fully loaded (that's, the "onload" event has fired) before returning control to yo ur test or script. It's worth noting that if your page uses a IoT of AJAX on load then Webdriver may not know when it had completely loaded.:

Driver.  Get("http://www.python.org")    

The next line is a assertion to confirm this title has a "Python" word in it:

Driver.  Title 

Webdriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can is located by its name attribute using find_element_by_namemetho D. Detailed explanation of finding elements is available in the locating elements Chapter:

Driver.  Find_element_by_name("Q")    

Next We are sending keys, which is the similar to entering keys using your keyboard. Special keys can be send using the keys class imported from Selenium.webdriver.common.keys:

Elem.  Send_keys("Pycon")elem.  Send_keys(keys.  RETURN)            

After submission of the page, you should get the result if there are any. To ensure that some results is found, make an assertion:

Driver.  Page_source 

Finally, the browser window is closed. You can also call quit method instead of close. The quit would exit entire browser whereas close ' would close one tab, but if just one tab is open, by default MoS T browser would exit entirely.:

Driver.  Close()  
1.3. Using Selenium to write tests

Selenium is mostly used for writing test cases. The Selenium package itself doesn ' t provide a testing tool/framework. You can write test cases using Python ' s unittest module. The other options for a tool/framework is py.test and nose.

In this chapter, we use unittest as the framework of choice. Here is the modified example which uses UnitTest module. This was a test for python.org search functionality:

ImportUnitTestFromSeleniumImportWebdriverFromSelenium.webdriver.common.keysImportKeysClassPythonorgsearch(UnitTest.TestCase):DefSetUp(Self):Self.Driver=Webdriver.Firefox()Deftest_search_in_python_org(Self):Driver=Self.DriverDriver.Get("Http://www.python.org")Self.Assertin("Python",Driver.Title)Elem=Driver.Find_element_by_name("Q")Elem.Send_keys("Pycon") elem. Send_keys (keys. Return) assert  "No results found." not in driver. Page_source def teardown (selfself. Driver. Close () if __name__ ==  "__main__" Span class= "P" >: unittest. Main ()               

Can run the above test case from a shell like this:

Python test_python_org_search.py.----------------------------------------------------------------------Ran 1 Test In 15.566sOK

The above result shows, the test has been successfully completed.

1.4. Walk through of the example

Initially, all the basic modules required is imported. The UnitTest module is a built-in Python based on Java's JUnit. This module provides the framework for organizing the test cases. The selenium.webdriver module provides all the Webdriver implementations. Currently supported Webdriver implementations is Firefox, Chrome, Ie and Remote. The keys class provide keys in the keyboard like RETURN, F1, ALT etc.

UnitTestwebdriverKeys 

The test case class was inherited from UnitTest. TestCase. Inheriting from TestCase class is the the-to-tell unittest module, which is a test case:

Class Pythonorgsearch (UnitTest. TestCase):

The setUp is part of initialization, this method would get called before every test function which you are going To write in the this test case class. Here is creating the instance of Firefox Webdriver.

SetUp(self): Self    .  Webdriver.  Firefox()        

This is the test case method. The test case method is should always start with characters test. The first line inside this method, create a local reference to the driver object created in setUp method.

Test_search_in_python_org(self): Self    .  Driver     

The driver.get method would navigate to a page given by the URL. Webdriver'll wait until the page has fully loaded (that's, the "onload" event has fired) before returning control to yo ur test or script. It's worth noting that if your page uses a IoT of AJAX on load then Webdriver may not know when it had completely loaded.:

Driver.  Get("http://www.python.org")    

The next line is a assertion to confirm this title has a "Python" word in it:

Self.  Assertin("Python"driver.  Title)       

Webdriver offers a number of ways to find elements using one of the find_element_by_* methods. For example, the input text element can is located by its name attribute using find_element_by_namemetho D. Detailed explanation of finding elements is available in the locating elements Chapter:

Driver.  Find_element_by_name("Q")    

Next We are sending keys, which is the similar to entering keys using your keyboard. Special keys can be send using the keys class imported from Selenium.webdriver.common.keys:

Elem.  Send_keys("Pycon")elem.  Send_keys(keys.  RETURN)            

After submission of the page, you should get result as per search if there are any. To ensure that some results is found, make an assertion:

Driver.  Page_source 

The TearDown method would get called after every test method. This was a place-to-do cleanup actions. The current method, the browser window is closed. You can also call quit method instead of close. The quit would exit the entire browser, whereas close would close a tab, but if it's the only tab opened, By default the most browser would exit entirely.:

TearDown(self): Self    .  Driver.  Close()        

Final lines is some boiler plate code to run the test suite:

"__main__":    unittest.  Main()    
1.5. Using Selenium with remote Webdriver

To use the remote Webdriver, you should has Selenium server running. To run the server with this command:

Java-jar Selenium-server-standalone-2.x.x.jar

While running the Selenium server, you could see a message looking like this:

15:43:07.541 Info-remotewebdriver instances should connect To:http://127.0.0.1:4444/wd/hub

The above line says so can use this URL for connecting to remote Webdriver. Here is some examples:

FromSelenium.webdriver.common.desired_capabilitiesImportDesiredcapabilitiesDriver=Webdriver.Remote(Command_executor=' Http://127.0.0.1:4444/wd/hub ',Desired_capabilities=Desiredcapabilities.Chrome)driver = webdriver. Remote (command_executor= ' http://127.0.0.1:4444 /wd/hub ' desired_capabilities= Desiredcapabilities. Opera) driver = webdriver. Remote (command_executor= ' http://127.0.0.1:4444 /wd/hub ' desired_capabilities= Desiredcapabilities. Htmlunitwithjs)              

The desired capabilities is a dictionary, so instead of using the default dictionaries, you can specify the values Explici tly

Webdriver.  Remotecommand_executor=' Http://127.0.0.1:4444/wd/hub 'desired_capabilities={' Browsername 'htmlunit 'version '2 'javascriptenabled 'True}   

Selenium-getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.