Selenium Tutorial: Simple Introduction to Use

Selenium is an automated testing tool that can be used to simulate user actions on a browser. It supports all major browsers and can be controlled through the Python API. Here are the basic steps for web automation testing with Selenium:

  1. Install Selenium

First you need to install the Selenium module. It can be installed with the pip command:

pip install selenium

   

    2. Download and set up Webdriver

Selenium needs to drive different browsers for testing. You need to download the corresponding webdriver and configure it in your system path. For example, if you want to test the Chrome browser, you need to download the corresponding version of chromedriver.exe. The latest version of the driver can be downloaded from the following link: https://sites.google.com/a/chromium.org/chromedriver/downloads

Before writing the code, you need to add the directory where chromedriver.exe is located to the PATH path of the system, so that Python can find the driver.

    3. Create a WebDriver instance

With a WebDriver instance, you can connect your Python program to a browser instance. For example, if you want to test Chrome:

from selenium import webdriver

driver = webdriver.Chrome()

This will launch a new Chrome browser window.

    4. Visit the webpage

get(url)A URL can be accessed through the method of the WebDriver instance :

driver.get("http://www.example.com/")

This method will open a new browser window and load the specified URL.

    5. Positioning elements

In automated testing, it is necessary to find the page elements to be operated, such as input boxes, buttons, etc. Elements can be positioned in the following ways:

Find elements by ID:

element = driver.find_element_by_id("element_id")

Find elements by name:

element = driver.find_element_by_name("element_name")

Find elements by tag name:

element = driver.find_element_by_tag_name("tag_name")

Find elements by class name:

element = driver.find_element_by_class_name("class_name")

Find elements by CSS selector:

element = driver.find_element_by_css_selector("css_selector")

Find elements by XPath:

element = driver.find_element_by_xpath("xpath_expression")

    6. Operating elements 

Through the positioned element, you can perform some actions, such as entering text, clicking a button, and so on. Here are some commonly used operations:

Enter text:

element.send_keys("input_text_here")

 Click the button:

element.click()

    7. Close WebDriver

After the test is complete, close the browser window and release resources by closing WebDriver:

driver.quit()

 These are the basic usages of Selenium. If you want to perform more advanced operations, such as handling multiple browser windows, waiting for the page to load, switching to an iframe, etc., you can refer to the official Selenium documentation or related tutorials.

Guess you like

Origin blog.csdn.net/weixin_40025666/article/details/131186481