user8114848
user8114848

Reputation: 173

Getting ID of Selenium WebElement in Python?

If I have the following HTML <a id="id" class="class" href="href">Element Text</a> how would I get "id" to be returned? My current procedure is:

print("Attribute: " + element.get_attribute('id'))
print("Property: " + element.get_property('id'))
print("Class: " + element.get_attribute('class'))

But all of those return empty strings. I am, however, able to get the text by using element.text

EDIT: Here's a more in depth explanation

I'm looking for an element but that element's ID varies. There is, however, an element linked to the element I want that I can find using it's xpath and comparing it's text to a specific text that I know beforehand. The ID of that element is something in the form of someID_XX. By taking the XX and appending it to another fixed string, I can then search for the element that I actually want. My issue is that once I get the second element (not the one I want directly, but the one that can lead me to the one I want) I can't seem to get it's ID attribute even though it seems to have one in the html. My question is, how do I get the id attribute?

Upvotes: 2

Views: 5056

Answers (1)

Rogelio Trivi&#241;o
Rogelio Trivi&#241;o

Reputation: 6519

For me is working with

element.get_attribute('id')

At the beginning didn't work because I selected incorrectly a hidden javascript element without id. But if the error persist on your case, you can try this:

element.get_attribute('outerHTML')

get the DOM for the element, and then parse the html to extract the id

Upvotes: 1

Related Questions