1

I am using the get_attribute() function in python with selenium to get a specific attribute from the children of a specific html element, however, some of the children do not have that attribute, is there a way to check if an html element has a specific attribute?

RafaelLeo
  • 27
  • 5

1 Answers1

0

You should iterate through direct children of that specific html element and check the desired attribute on each of them individually.

To get all the direct children one way is to use CSS selectors:

find_elements_by_css_selector("your_element > *")

The above gives you the list of childrens, then iterate over it and check if each element has the attribute you want using get_attribute().

If you already have the element, you can use XPATH as well:

e.find_elements_by_XPATH('./*')

note: find_elements_by_* commands are now deprecated. It's better to use find_elements(By.XPATH) for example.

S.B
  • 13,077
  • 10
  • 22
  • 49
  • hi, thank you for the answer, I am just confused on how I would check if an element has an attribute, but thanks a lot for the help :D – RafaelLeo Nov 27 '21 at 00:44
  • @RafaelLeo write a for loop, `for element in lst:` lst here is the returned list from the above commads you saw in the answer. then call `element.get_attribute('...)` and check the return value. If it doesn't have that attribute it returns None. – S.B Nov 27 '21 at 00:48
  • alr, ty for all the help :) – RafaelLeo Nov 27 '21 at 02:37