python - selenium python webdriver 有没有办法断言所有复选框都已选中或未选中?

标签 python selenium checkbox selenium-webdriver

我正在构建一个测试来检查单个页面上许多复选框的状态。

有没有办法可以使用循环或类似的东西来断言它们都已检查或未检查?我是 python 和 python webdriver 的新手,所以我什至不确定如何开始这样的事情。

我在 java 中看到了类似问题的答案,但在 python 中却没有看到。

感谢您的帮助。

@Anzel,这是我正在使用的代码:

checkboxes = driver.find_elements_by_xpath('.//input[@type="checkbox"]')
[c.is_selected() for c in checkboxes]
[True, True, False, False, False, False, False, False, False]
assert all([c.is_selected() for c in checkboxes])

这会出现以下错误:

Traceback (most recent call last):
File "test.py", line 71, in test_test
assert all([c.is_selected() for c in checkboxes])
AssertionError

感谢您的帮助。

最佳答案

是的,您可以使用is_selected()来测试该元素是否被选中。如果你使用find_elements_by_xxx(),那么你只需要循环它和assert他们的结果。

让我们看一个示例:

from selenium import webdriver

driver = webdriver.Firefox()
url = 'http://www.tizag.com/htmlT/htmlcheckboxes.php'
driver.get(url)
checkboxes = driver.find_elements_by_name('sports')

# simply use is_selected() can yield their Selected status
[c.is_selected() for c in checkboxes]
[False, False, False, False, True, False, False, True]
<小时/>
# to assert they are all unchecked, use not any()
assert not any([c.is_selected() for c in checkboxes])


# so to assert they are all checked, just use all()
assert all([c.is_selected() for c in checkboxes])

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-661-c6f9ba4afaf2> in <module>()
----> 1 assert all([c.is_selected() for c in checkboxes])

AssertionError: 
<小时/>

更新:

您可以简单地通过 xpath 找到所有复选框,这通常有效:

driver.find_elements_by_xpath('.//input[@type="checkbox"]')

但这并不能保证,您确实需要不时提出自定义解决方案。

这是 Webdriver 支持的列表 find元素:

[_ for _ in dir(driver) if 'find' in _]
Out[10]: 
['find_element',
 'find_element_by_class_name',
 'find_element_by_css_selector',
 'find_element_by_id',
 'find_element_by_link_text',
 'find_element_by_name',
 'find_element_by_partial_link_text',
 'find_element_by_tag_name',
 'find_element_by_xpath',
 'find_elements',
 'find_elements_by_class_name',
 'find_elements_by_css_selector',
 'find_elements_by_id',
 'find_elements_by_link_text',
 'find_elements_by_name',
 'find_elements_by_partial_link_text',
 'find_elements_by_tag_name',
 'find_elements_by_xpath']

显然没有 by_type ,所以它会给你一个 AttributeError

关于python - selenium python webdriver 有没有办法断言所有复选框都已选中或未选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182538/

相关文章:

Python - 访问顶级变量的更快方法

jquery - 将更改事件绑定(bind)到每个 DataTables 行中的复选框

css - Chrome 83:更改新表单样式的颜色

php - 使用 For Each 使用 JSON 对象更新 MySQL -- 复选框

python从arduino读取串行输出

python - 在 matplotlib 中翻转绘图

python - 获取 Inkscape SVG 元素旋转的绝对坐标

python - 使用 Selenium 时出错 (Python) : Unable to find class in HTML source code

javascript - Chrome 扩展程序可以修改 Window 对象,但无法创建新变量

javascript - 使用 jasmine 测试 javascript UI 的最佳方法