简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM