问题
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?
回答1:
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:
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 (here are some docs, is_selected
is 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_selected
appeared).
回答2:
I'm using driver.find_element_by_name("< check_box_name >").is_selected()
回答3:
I find another way that works, but uses javascript inside.
def is_checked(self, driver, item):
checked = driver.execute_script(("return document.getElementById('%s').checked") % item)
return checked
回答4:
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
来源:https://stackoverflow.com/questions/14442636/how-can-i-check-if-a-checkbox-is-checked-in-selenium-python-webdriver