Selenium / Python - Selecting via css selector
Issue:
Can not select from css selector specific element. Need to verify that the registered user can change their password successfully. I have tried the different attributes of the class to call it. The result is an exception error in the method when trying with the first two examples. The final try calls the first class instance and resets the password fields (fail).
Tried:
driver.find_element_by_css_selector("value.Update").click()
driver.find_element_by_css_selector("type.submit").click()
driver.find_element_by_css_selector("input.test_button4").click()
Objective:
I need to select items that share the same class. As you can see below, the class is shared.
form id="changepw_form" name="changepw" action="#" method="post">
<div class="field3">
<div class="field3">
<div class="field3">
<input class="test_button4" type="reset" value="Reset" style"font-size:21px"="">
<input class="test_button4" type="submit" value="Update" style"font-size:21px"="">
Solution 1:
driver.find_element_by_css_selector(".test_button4[value='Update']").click()
EDIT:
Because the selector needs a class
, id
, or tagname
, but value.Update
by itself is none of these.
.test_button4
provides a classname to match against, and from there, [value='Update']
specifies which particular match(es) to select.
Solution 2:
test_button4 = driver.find_elements_by_class_name('test_button4') # notice its "find_elementS" with an S
submit_element = [x for x in test_button4 if x.get_attribute('value') == 'Update'] #this would work if you had unlimited things with class_name == 'test_button4', as long as only ONE of them is value="Update"
if len(submit_element): # using a non-empty list as truthiness
print ("yay! found updated!")
This is something that i hardly ever see anyone document, explain, or use.
(ill use name for example because its simplest)
find_element_by_name()
returns a single item, or gives an exception if it doesnt find it
find_elements_by_name()
returns a list of elements. if no elements found, the list is empty
so if you do a find_elements_by_class_name()
and it returns a list with X entries in it, all thats left at that point to narrow down what you want is either some old fashioned list comprehension ( like how i used in my answer ) or some indexing if you for some reason know which element you want.
also get_attribute()
is seriously under-utilized as well. it parses the inside of the elements html by using what is before the =
and returns what is after the =