如何使用 Python 和 Selenium 统计页面中复选框的数量?
我们可以使用 find_elements 方法来统计 Selenium 中页面中复选框的总数。在处理任何复选框时,我们总会在 HTML 代码中找到一个 type 属性,其值应为 checkbox。
此特性仅适用于该页面上的复选框,而不适用于其他类型的 UI 元素,如编辑框、链接等。
要检索所有具有属性 type = 'checkbox' 的元素,我们将使用 find_elements_by_xpath() 方法。此方法返回一个包含 xpath 类型为方法参数中指定的 web 元素的列表。如果没有匹配的元素,则返回一个空列表。
获取复选框列表后,为了统计其总数,我们需要获取该列表的大小。列表的大小可以通过列表数据结构的 len() 方法获得。
最后,此长度将打印到控制台。
语法
driver.find_elements_by_xpath("//input[@type='checkbox']")示例
统计复选框的代码实现。
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the checkboxes with type attribute in a list
chk =driver.find_elements_by_xpath("//input[@type='checkbox']")
# len method is used to get the size of that list
print(len(chk))
#to close the browser
driver.close()
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP