如何检查是否在 Selenium Python Webdriver 中选中了复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14442636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if a checkbox is checked in Selenium Python Webdriver?
提问by Júlio Griebeler
I'm searching a week how check if a checkbox is checked in selenium webdriver with python, but I find only algoritms from JAVA. I readed the webdriver docs and it dont have a answer for that. Anyone have a solution?
我正在搜索一周如何检查是否使用 python 在 selenium webdriver 中选中了一个复选框,但我只找到了来自 JAVA 的算法。我阅读了 webdriver 文档,但没有答案。有人有解决方案吗?
采纳答案by Júlio Griebeler
I find another way that works, but uses javascript inside.
我找到了另一种有效的方法,但在里面使用了 javascript。
def is_checked(self, driver, item):
checked = driver.execute_script(("return document.getElementById('%s').checked") % item)
return checked
回答by RocketDonkey
There is a WebElement property called is_selected(), and for a check box this indicates whether or not it is checked. Therefore you can verify if it is checked/unchecked by doing something like this:
有一个名为 的 WebElement 属性is_selected(),对于复选框,这表明它是否被选中。因此,您可以通过执行以下操作来验证它是否被选中/取消选中:
driver.find_element_by_name('<check_box_name>').is_selected()
or
或者
driver.find_element_by_id('<check_box_id>').is_selected()
I remember having the same issue not being able to find documentation. It's easier to find once you know the name (hereare some docs, is_selectedis towards the bottom), but the way I have gone about trying to find different options/properties for Selenium objects is to just drop dir(some_object)in the code and see what options come up (this is how is_selectedappeared).
我记得有同样的问题无法找到文档。一旦您知道名称(这里有一些文档,is_selected位于底部),就更容易找到,但是我尝试为 Selenium 对象查找不同选项/属性的方法是dir(some_object)放入代码并查看有哪些选项up(这是如何is_selected出现的)。
回答by Feten besbes
def assert_checkbox_status (id, expect):
global browser
field = browser.find_element_by_id(id)
assert field.get_attribute ('checked')== expect
Example of use:
使用示例:
assert_checkbox('activate', True) ==> assert if checkbox is checked
assert_checkbox('activate', None) ==> assert if checkbox is unchecked
回答by Andrew
I'm using driver.find_element_by_name("< check_box_name >").is_selected()
我正在使用 driver.find_element_by_name("< check_box_name >").is_selected()
回答by Ali Shah
var = driver.find_element_by_id("id/checkBoxAgreed")
if var.get_attribute("checked") == "true":
var.click()

