Selenium-element positioning method

Locating elements is a common and important task when automating with selenium. Accurate selection of elements is a critical step in the testing process.
This article will introduce commonly used element positioning methods to help you better understand and apply these methods.

How to select elements

There are many ways to locate elements, which can be selected according to the characteristics of the elements. Here are some commonly used element positioning methods:

  1. ID positioning: Use the ID attribute of the tag to locate the element. The syntax is as follows:

    元素对象 = driver.find_element_by_id('id属性值')
    
  2. According to the name attribute: Use the name attribute of the tag to locate the element. If there are multiple identical name attributes on the page, the first matching element will be used by default. The syntax is as follows:

    元素对象 = driver.find_element_by_name('name属性')
    
  3. class_name positioning: Use the class attribute of the tag to locate the element. A tag can have multiple class attribute values, and multiple class attribute values ​​are separated by spaces, but only one of them can be selected when locating. The syntax is as follows:

    元素对象 = driver.find_element_by_class_name('class属性值')
    
  4. Tag_name positioning: use the name of the tag to locate the element. The syntax is as follows:

    元素对象 = driver.find_element_by_tag_name('标签名')
    
  5. link_text positioning: It can only be used for hyperlink tags (a tags), and is positioned according to the entire text content of the a tag. The syntax is as follows:

    元素对象 = driver.find_element_by_link_text('a标签的全部文本内容')
    
  6. partial_link_text positioning: It can only be used for hyperlink tags (a tags), and is positioned according to the partial text content of the a tag. The syntax is as follows:

    元素对象 = driver.find_element_by_partial_link_text('a标签的部分文本内容')
    
  7. xpath path expression: using xpath to locate elements is one of the most commonly used positioning methods. The syntax is as follows:

    元素对象 = driver.find_element_by_xpath('xpath路径表达式')
    
  8. CSS selector selection: Using CSS selectors to locate elements is also one of the commonly used positioning methods. The syntax is as follows:

    元素对象 = driver.find_element_by_css_selector('css选择器选择')
    
    

    sample code

    Here's a sample code that shows how to use the targeting methods above:

    # 导包
    from selenium import webdriver
    import time
    
    # 创建浏览器驱动对象
    driver = webdriver.Chrome()
    
    # 打开要测试的页面
    driver.get("https://www.baidu.com/")
    
    # 书写具体的业务步骤(用例的步骤)
    # 输入关键字"ui自动化",点击搜索按钮
    driver.find_element_by_id('kw').send_keys('ui自
    
    

Please note that after Selenium version 4, the find_element_by* method is marked as outdated and not recommended. It is recommended to use find_element combined with the By class to define

Guess you like

Origin blog.csdn.net/AAIT11/article/details/130782098