Original URL: https://www.guru99.com/selenium-python.html
How to Use Selenium with Python: Complete Tutorial
Selenium supportsPythonand thus can be utilized with Selenium for testing.
- Python is easy compared to other programming languages, having far less verbose.
- The Python APIs empower you to connect with the browser through Selenium.
- Selenium sends the standard Python commands to different browsers, despite variation in their browser‘s design.
You can run Python scripts for Firefox, Chrome, IE, etc.ondifferent Operating Systems.
In this tutorial, you will learn-
- What is Python?
- What is Selenium?
- Why to choose Python over Java in Selenium
- Install and Configure PyDev in Eclipse
- Create Test Scripts in Selenium with Python
What is Python?
Python is a high-level object-oriented scripting language. It is designed in a user-friendly manner. Python uses simple English keywords, which is easy to interpret. It has less syntax complications than any other programming languages.
See some of the examples in the table below.
Keyword | Meaning | Usage |
elif | Else if | Else if |
else | Else | if: X; elif: Y; else: J |
except | do this ,If an exception happens, | except ValueError, a: print a |
exec | Run string as Python | exec ‘print "hello world !"‘ |
What is Selenium?
Selenium is a tool to test your web application. You can do this in various ways, for instance
- Permit it to tap on buttons
- Enter content in structures
- Skim your site to check whether everything is "OK" and so on.
Why to choose Python over Java in Selenium
Few points that favor Python overJavato use with Selenium is,
1. Java programs tend to run slower compared to Python programs.
2. Java uses traditional braces to start and ends blocks, while Python uses indentation.
3. Java employs static typing, while Python is dynamically typed.
4. Python is simpler and more compact compared to Java.
Install and Configure PyDev in Eclipse
PyDev is Python development environment for Eclipse.
Step 1) Got to Eclipse Marketplace. Help > Eclipse Marketplace
Now once the plugin ‘eclipse market place‘ is opened. The next step is to install "pydev IDE" for eclipse.
Step 2) In this step,
- Search for "pydev" in search box and then
- Click install(In my system it is already installed).
Step 3) Select the checkbox button. It says ‘PyDev.‘ The first check box is mandatory while the second one is optional. After marking the checkbox, press ‘Next‘.
Step 4) Now, in this step you will set preferences. With the help of preference option, you can use Python as per the project need.
Go to Windows > Preferences > Interpreter-Python. Click on "OK" button.
A new window will open when you click on ‘OK‘ button. In this window, follow the following steps.
- Under interpreter dropdown, you select the option Interpreter-Python. It helps in running Python scripts.
- Also, set workbench time interval. When a build is performed, the workbench will automatically save all resources that is changed since the last build.
- Click on ‘OK‘ button.
When you click on"OK" button, it sets the default Python Interpreter. It is just like you need to set java compiler for running a Java code. To change the interpreter name, double click on Python Tab.
Step 5)In this step, give the "interpreter name" and the "exe file name" of Python.
- Click on ‘Browse‘ and find python.exe "C:\Python27\python.exe.
- Click ‘OK‘ button.
Step 6) Make a New Project in Python. In this step,
- Right click Package Explorer > New >
- Select option others.
You can see the new Python(PyDev) project is created.
Step 7) In this step,
- Select ‘PyDev Project‘ and
- Press ‘Next‘ button.
After creating ‘PyDev Project‘, you will create a new Python package.
Step 8) Create a new Python package. After entering the name, click on "Finish" button.
If you see in below screenshot, a new package is created.
After creating a new package, the next step is to createPyDev Module. The module contains somePython files for initialization. These files or functions from the module can be imported into other module. So, there will be no need to re-write the program again.
Step 9) Createa new PyDev module. Right click on package > New >Other>PyDev module.
Step 10) Write your Python code.
Create Test Scripts in Selenium with Python
- In this example, we did automation for "Facebook login page" using the Firefox driver.
EXAMPLE 1
from selenium import webdriver from selenium.webdriver.common.keys import Keys user = "" pwd = "" driver = webdriver.Firefox() driver.get("http://www.facebook.com") assert "Facebook" in driver.title elem = driver.find_element_by_id("email") elem.send_keys(user) elem = driver.find_element_by_id("pass") elem.send_keys(pwd) elem.send_keys(Keys.RETURN) driver.close()
Snapshot of the Code
Explanation of the code
- Code line 1: From selenium module import webdriver
- Code line 2: From selenium module import Keys
- Code line 3: User is a blank variable which will be we used to store values of username.
- Code line 4: pwd is also a blank (here it is empty, but the user can provide values in it) variable. This will be used to store values of the password.
- Code line 5: In this line, we are initializing "FireFox" by making an object of it.
- Code line 6: The "driver.get method" will explore to a page given by the URL.WebDriver will hold up until the page has completely been loaded (that is, the "onload" occasion has let go), before returning control to your test or script.
- Code line 7: "Asserts" keyword is used to verify the conditions. In this line, we are confirming whether the title is correct or not. For that, we will compare the title with the string which is given.
- Code line 8: In this line, we are finding the element of the textbox where the "email" has to be written.
- Code line 9: Now we are sending the values to the email section
- Code line 10: Same for the password
- Code line 11: Sending values to the password section
- Code line 12: Elem.send_keys(Keys.RETURN) is used to press enter after the values are inserted
- Code line 13: Close
OUTPUT
The values of the username "guru99" and password entered.
The Facebook page will login with email and password. Page opened (see image below)
EXAMPLE 2
In this example,
- We will open a login page.
- Fill the required field"username" and "password".
- Then validate if the login was successful or not.
from selenium import webdriver from selenium.common.exceptions import TimeoutException browser = webdriver.Firefox() browser.get( www.facebook.com ) username = browser.find_element_by_id( "guru99" ) password = browser.find_element_by_id( "[email protected]" ) submit = browser.find_element_by_id( "submit" ) username.send_keys( "me" ) password.send_keys( "mykewlpass" ) submit.click() wait = WebDriverWait( browser, 5 ) try: page_loaded = wait.until_not( lambda browser: browser.current_url == login_page ) except TimeoutException: self.fail( "Loading timeout expired" ) self.assertEqual( browser.current_url, correct_page, msg = "Successful Login" )
Snapshot of the code
Explanation of the code:
- Code line 1-2: Import selenium package
- Code line 4: Initialize Firefox by creating an object
- Code line 5: Get login page (Facebook)
- Code line 7-9: Fetch username, password input boxes and submit button.
- Code line 11-12: Input text in username and password input boxes
- Code line 15: Click on the "Submit" button
- Code line 18: Create wait object with a timeout of 5 sec.
- Code line 20 -30: Test that login was successful by checking if the URL in the browser changed. Assert that the URL is now the correct post-login page
Note: For the above scenarios there will be no output. Since no valid URL is used in the example.
Summary:
- Selenium is an open-source web-based automation tool.
- Python language is used with Selenium for testing. It has far less verbose and easy to use than any other programming language
- The Python APIs empower you to connect with the browser through Selenium
- Selenium can send the standard Python commands to different browsers, despite variation in their browser‘s design.
原文地址:https://www.cnblogs.com/alicegu2009/p/9098727.html