码迷,mamicode.com
首页 > 编程语言 > 详细

[Selenium+Java] How to Use Selenium with Python: Complete Tutorial

时间:2018-05-28 11:33:16      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:cep   sign   created   exception   AC   NPU   cti   nload   designed   

Original URL: https://www.guru99.com/selenium-python.html

How to Use Selenium with Python: Complete Tutorial

Selenium supports Python and 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?

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 over Java to 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,

  1. Search for "pydev" in search box and then
  2. 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) Nowin 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.

  1. Click on ‘Browse‘ and find python.exe "C:\Python27\python.exe.
  2. Click ‘OK‘ button.

技术分享图片

Step 6) Make a New Project in Python. In this step,

  1. Right click Package Explorer > New >
  2. Select option others.

技术分享图片

You can see the new Python(PyDev) project is created.

技术分享图片

技术分享图片

Step 7) In this step,

  1. Select ‘PyDev Project‘ and
  2. 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( "password@123" )
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.

[Selenium+Java] How to Use Selenium with Python: Complete Tutorial

标签:cep   sign   created   exception   AC   NPU   cti   nload   designed   

原文地址:https://www.cnblogs.com/alicegu2009/p/9098727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!