Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Construction and Operation of Python+Selenium Automation Environment

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the example analysis of the construction and operation of Python+Selenium automation environment, which is very detailed and has a certain reference value. Interested friends must read it!

1. Setting up the environment 1. Python installation

Download address: click here to download

Select the appropriate version to install

Choose according to your operating system type and number of bits.

WINDOS + R input cmd

Open the DOS window and check that the environment variables are configured correctly

(1) python-V, which returns the python version number

(2) pip-V, which returns the pip tool version number

2. Download and install pycharm

(1) download pycharm

Download address: click here to download

On the right is the community version, open source and free

Professional version on the left, for a fee

(2) installation

To run the exe program, click [Next]

After selecting the installation directory, click [Next]

Click [Next] after checking the relevant options.

Click [Install] to complete the installation

Just wait for the installation to complete.

Click [Finish] to complete the installation

(3) create a project

Run pycharm and click [New Project]

Configure project basic information

(1) Select the storage path for the project

(2) selecting the Python library that the project depends on will create a venv virtual environment in the project.

(3) Associate with the local Python interpreter. If you do not want to use venv, you can select the executable file of the local interpreter.

It is recommended that you select New environment using, and then select the path to the previously installed Python interpreter in Base interpreter. The advantage of this: each project is a separate space, there will not be the problem of version-dependent conflicts, and scoring gives play to the flexibility of the virtual environment. After the modification, click Creat to create the project. This creates an initial empty project

Create script

Right-click on the project name to create a python file

Enter the name of the script and press enter to create the file

3. Download and install selenium

(1) download via pip command

WINDOS + R enter CMD to open the DOS window

Input: pip insatall selenium

If the following occurs during installation, it is a problem with the pip version

Enter: python.exe-m pip install-- upgrade pip just upgrade the version

After the installation is complete, you can view it in the python > lib > site-packages directory

(2) download via pycharm

Open pycharm and click [file] in the upper left corner to select settings.

Select the project and click [+]

Enter selenium, select the appropriate version (you can not select the version), double-click to install

(3) download the selenium installation package

Download address: click here to download

After the download is completed, put it in the python > lib > site-packages directory

Or

The location of the project is D:\ pythonProject\ venv\ Lib\ site-packages

4. Download and install browser driver

Attention! The driver version must be consistent with the browser version

Check the browser version in the browser settings. Use Edge browser for example: version number: version 96.0.1054.62

The driver is downloaded and placed in the python root directory.

(1) download and install Edge driver

Download address: click here to download

Note that the version is consistent and the system is consistent

(2) download and install Chrome driver

Download address: click here to download

The latest version of the Chrome driver browser is located near the bottom of the web page.

Click the corresponding version to go in.

Click on the file to download automatically

(3) download and install IE driver

Download address: click here to download

There is a version 4.0 IE driver on the official website, which can be downloaded by clicking on it.

Download address for other versions:

Download address: click here to download

(4) download and install Firefox driver

Download address: click here to download

Here is the version number:

Download here:

In addition, this website can also be downloaded

Download address: click here to download

II. Brief introduction of Selenium

What is Selenium?

Selenium is an open source automated testing tool for Web applications. By writing scripts that simulate user actions, it opens a browser to test Web applications in a black box. It can be easily used for functional testing, compatibility testing, stability testing and concurrent testing. At present, it has been widely supported by mainstream browser manufacturers, and it is also the underlying core technology of many other automated testing tools, such as RobotFramework. Selenium consists of four projects: IDE, Remote Control (RC for short), WebDriver and Grid:

(1) Selenium IDE

Is an Firefox add-on for recording / playing back test scripts that generate Selenium RC-based test code (Java, Ruby, C #, etc.). Suitable for getting started, but not suitable for actually large test projects

(2) Selenium RC

RC consists of Server and Client. Server is responsible for loading / closing browsers and accessing Web applications as HTTP proxies. Clinet supports multiple programming languages and testing frameworks (TestNG, JUnit, NUnit, etc.).

(3) Selenium WebDriver

WebDriver, as the core feature of Selenium2, provides API, which is more concise and easy to use than RC, and is an officially recommended alternative to RC. Can better support dynamic web pages, do not need to start a separate Server.

(4) Selenium Grid

Is an extension tool for Selenium that makes it easy to run multiple RC or WebDriver use cases in parallel on multiple machines and in heterogeneous environments.

3. Common methods 1. Browser operation

Open the browser: (you must have the appropriate driver. If you can't open it, there is basically a problem with the driver configuration.)

-webdriver.Chrome () # Open Google browser-webdriver.Firefox () # Open Firefox-webdriver.Edge () # Open Edge browser-webdriver.Ie () # Open IE browser-webdriver.Safari () # Open Safari browser-webdriver.Opera () # Open Opera browser

Close the browser

-quit () # exit browser-exit entire browser-close () # close browser-current page [cannot be closed when multiple pages are open]-os.system ('taskkill / im chrome.exe / F') # kill process

Refresh browser

Dr.refresh () # Refresh

Forward and backward

Dr.forward () # forward dr.back () # back

Resize the window

Dr.maximize_window () dr.minimize_window () dr.set_window_size (300400)

Access URL address

Dr.get ('http://192.168.14.162:8081/agileone1/')2, how to get page elements

First open the browser and press F12 to enter developer mode

Click the three points in the upper right corner to select the docking location of the development box, and click on the element to view the details of the page attributes.

Using the shortcut CTRL+SHIFT+C in the upper left corner of the development bar, when you hover over an element, you will automatically navigate to the location of the HTML element.

When we locate the element, we can see which attributes it contains and which attributes are appropriate for positioning:

Attribute positioning priority: ID > Name > CSS > XPath

A quick way to copy element attribute values:

1. Select the appropriate attribute and double-click CTRL+C

2. Navigate to the attribute and select the mouse message to copy (COPY)-> Select the appropriate type.

3. The method of finding and locating page elements

Method 1:

Get a single element (sometimes it will indicate that this method has been abandoned, you can choose the second way to get it)

-driver.find_element_by_id ('username') # get through id-driver.find_element_by_class_name (' login-password') # get through class-driver.find_element_by_name ('') # get-driver.find through name attribute _ element_by_link_text ('announcement management') # get through hyperlink text-driver.find_element_by_partial_link_text ('announcement management') # get through hyperlink text section-driver.find_element_by_css_selector ('input#username.login-username') # get-driver.find_element_by_tag_name through CSS ( 'input') # locate through tag name-driver.find_element_by_xpath (' / * [@ id= "username"]) # locate via xpath

Batch element acquisition

Driver.find_elements_by_ property name ('attribute value')

Example:

Driver.find_elements_by_class_name ('form-control') [0] .send _ keys (' admin')

Method 2:

Need to import module from selenium.webdriver.common.by import By

Get a single element:

-driver.find_element (by=By.ID,value= "attribute value") # locate through ID-driver.find_element (by=By.XPATH,value= "attribute value")-driver.find_element (by=By.CLASS_NAME,value= "attribute value")-driver.find_element (by=By.CSS_SELECTOR,value= "attribute value")-driver.find_element (by=By.NAME,value= "attribute value")-driver.find_element (by=By.LINK_TEXT Value= "property value")-driver.find_element (by=By.TAG_NAME,value= "property value")-driver.find_element (by=By.PARTIAL_LINK_TEXT,value= "property value")

Multi-element acquisition:

Driver.find_elements (by=By.ID,value=' property value') [index location] .send_keys ('input')

Example:

Driver.find_elements (by=By.ID,value='username') [0] .send _ keys ('admin') 4, operation method code operation send_keys (' input content') input text click () Click clear () clear text to get text information double_click double-click context_click right move_to_element hover drag_and_drop (before After) drag 5, drop-down box operation Select (driver.find_element_by_id ('scope')). Select_by_visible_text (' all items') # according to the text Select (driver.find_element_by_id ('scope')). Select_by_index (1) # based on index location Select (driver.find_element_by_id (' scope')). Select_by_value ('0') # based on value 6, WINDOS pop-up window driver.switch_to.alert (). Accept () # alert-- prompt confirmation: driver.switch_to.alert.dismiss () # cancel driver.switch_to.alert.send_keys () # text prompt driver.switch_to.alert.text # get the text information in the prompt box 7. Iframe embedded page processing

Processing iframe pages embedded in HTML pages (one HTML page wrapped in another HTML page)

The first choice is to navigate to the embedded page:

Iframe=driver.find_element (by= "xpath", value= "/ html/body/div [2] / div [3] / div [1] / div/div [4] / div [1] / div [1] / iframe")

And then switch focus.

Driver.switch_to.frame (iframe) # switch to embedded page

Perform the operation after switching

Driver.find_element (by= "name", value= "email"). Clear () # clears the content time.sleep (0.5) driver.find_element (by= "name", value= "email"). Send_keys ("a123456") # enter the account time.sleep (0.5) driver.find_element (by= "name" Value= "password") .clear () # clear content time.sleep (0.5) driver.find_element (by= "name", value= "password"). Send_keys ("a123456") # enter the password time.sleep (0.5) driver.find_element (by= "id", value= "dologin"). Click () # Click to enter the home page of the mailbox

Switch to the parent interface after execution is complete

Driver.switch_to.parent_frame () # switch back to parent page 8, upload files

1. For and tags and type=file types, you can directly enter send_keys.

Driver.find_element_by_id ("imgfile") .send_keys ("D:\ pictyres\ selenium.png")

2. Upload files using keyboard events

Pykeyboard module needs to be installed

Driver.find_element_by_xpath ('element location'). Click () pk=PyKeyboard () # instantiate pk.type_string (r 'file path') pk.press_key (pk.enter_key) # Press pk.release_key (pk.enter_key) # release 9, switch pages

Handle switch driver.switch_to.window ('new handle')

For handle in driver.window_handles: # traversal if handle! = driver.current_window_handle: driver.switch_to.window (handle) # handle toggles driver.swithch_to_window (driver.window_handles [- 1]) print (driver.current_window_handle) 10, Screenshot driver.get_screenshot_as_file (filename) driver.save_screenshot (filename) driver.get_screenshot_as_png () driver.get_screenshot_as_base64 ()

The following is a method for me to take screenshots and write them to the database in practical application.

11. Waiting time

Force wait:

First of all, you need to guide the package import time

Time.sleep (2), which is often used to get the setting before text, in second

Implicit wait:

When commonly used for initialization, set the global wait

Dr.implicitly_wait (5)

Show wait:

It is often used to specify that an element can be operated only when it appears.

WebDriverWait (driver=dr,timeout=5,poll_frequency=0.5) .injection (lambda dr:dr.find_element_by_link_text ('logout') 12, js injection

(1) Slide to the specified position

Target = driver.find_elements_by_class_name (f "attribute value") [0] # get element driver.execute_script ("arguments [0] .scrollIntoView ();", target) # slide to the specified element location

(2) sliding up and down the page

Driver.execute_script ('window.scrollBy (0600)') # glide page driver.execute_script ('window.scrollBy (0LRIMART 600)') # Slide page 13, assertion method and strategy

When asserting, you should use the and method to override the following assertion methods whenever possible

1. Check whether the text prompt message meets the expectation

two。 Check whether the data background data is correct (background front end)-database assertion table field pymysql connection cursor SQL to get the result

3. Business Loki assertions: select associated functions to determine correctness, such as uploading files, asserting whether search files exist and are consistent

4. Assertion method

Is_displayed () shows that there is

The above is all the contents of the article "sample Analysis of the Construction and Operation of Python+Selenium Automation Environment". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report