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

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?

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,

  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( "[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

时间: 2024-10-11 22:46:12

[Selenium+Java] How to Use Selenium with Python: Complete Tutorial的相关文章

Selenium+Java(七)Selenium对话框的处理

HTML代码如图所示: 一.alert String url = "file:///C:/Users/ex_yuhao/Desktop/index.html"; //引用IE浏览器驱动 System.setProperty("webdriver.ie.driver", "./src/driver/IEDriverServer.exe"); //创建IE浏览器对象 InternetExplorerDriver driver = new Intern

selenium + java + testNG 自动化环境搭建

kSelenium终极自动化测试环境搭建(一)Selenium+Eclipse+Junit+TestNG 第一步 安装JDK JDk1.7. 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html 一路猛击'下一步',OK.安装完成后配置环境变量: JAVA_HOME = E:\Java\Java\jdk1.7.0_15 PATH = %JAVA_HOME%\bin CLAS

selenium第一课(selenium+java+testNG+maven)

selenium介绍和环境搭建 一.简单介绍 1.selenium:Selenium是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE.Mozilla Firefox.Chrome等.支持自动录制动作和自动生成,Net.Java.Python等不同语言的测试脚本.Selenium 测试脚本可以在 Windows.Linux 和 Macintosh等多种平台上运行. 2.TestNG:TestNG是一个测试框架,其灵感来自JU

selenium+java+testNG+maven环境搭建

一.简单介绍 1.selenium: Selenium是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE.Mozilla Firefox.Chrome等.支持自动录制动作和自动生成,Net.Java.Python等不同语言的测试脚本.Selenium 测试脚本可以在 Windows.Linux 和 Macintosh等多种平台上运行. 2.TestNG: TestNG是一个测试框架,其灵感来自JUnit和NUnit的,但引入

Selenium+Java+Eclipse 自动化测试环境搭建

一.下载Java windows java下载链接 https://www.java.com/zh_CN/download/win10.jsp 二.安装Java 安装好后检查一下需不需要配置环境变量,现在java 8已经不用配置环境变量了,直接在命令行输入:java -version 三.下载和安装Eclipse windows Eclipse下载链接 https://www.eclipse.org/downloads/ 你也可以下载绿色版 四.下载selenium,然后解压 selenium

软件测试之Selenium Java WebDriver

编写Selenium Java WebDriver程序,测试inputgit.csv表格中的学号和git地址的对应关系 package selenium2; import java.util.regex.Pattern; import java.util.concurrent.TimeUnit; import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import o

自动化测试框架selenium+java+TestNG——配置篇

最近来总结下自动化测试 selenium的一些常用框架测试搭配,由简入繁,最简单的就是selenium+java+TestNG了,因为我用的是java,就只是总结下java了. TestNG在线安装: 打开Eclipse   Help ->Install New Software ,   然后Add   "http://beust.com/eclipse" 选择TestNG,finish下一步完成安装. 验证是否安装成功 File->new->other 导入sele

Selenium Java WebDriver 使用

一. Firefox安装Selenium插件 在FireFox的菜单中的附加组件中搜索Selenium IDE 然后安装 二. 使用Selenium IDE录制脚本/导出脚本 点击图中标志打开Selenium IDE 红色按钮按下表示正在录制,这时候只用将界面切换到Firefox,网址中输入www.baidu.com,然后再搜索框中输入文字,点击搜索,所有的控件的访问都会被记录下来,然后切换回seleniumIDE就可以看到已经录制完毕 然后在图中红色选中的区域可以调整重新执行的速度,蓝色选中区

selenium+java:获取列表中的值

selenium+java:获取列表中的值 (2011-08-23 17:14:48) 标签: 杂谈 分类: selenium 初步研究利用java+testNg框架下写selenium测试用例,今天学会了几个API:(1)获取页面上列表中的值,并打印输出:System.out.println(selenium.getTable("xpath=/html/body/div[3]/form/table.1.1")); //输出列表中第1行第1列的值(2)判断页面上是否有某个文本:(只能判