Mal229 Mal229 - 3 years ago 176
Python Question

Selenium: get ID of a div with a class that has a space

I have a div that has a class of 'message clearfix default' with a subclass of 'data-message-id=XX'. My goal is to get that id 96375050. ive tried the .find_element_by_class_name however the class is 'message clearfix default' and it fails due to the spaces. Also since this is not a displayed piece there is not CSS to attach too.

enter image description here

How can I get 96375050 back?

<div class="message clearfix default" data-message-id="96375050" data-user-id="186772" data-user-login="MAS1271" id="message_96375050" data-ape="messages_96375050">

Answer Source

You can use find_element_by_xpath to get the element:

elem = driver.find_element_by_xpath('//li[@class="messageli"]//div[@class="message clearfix default"]')
msg_id = elem.get_attribute('data-message-id')

[@class="text"] uses exact matching , you can combine and&contains like:

elem = driver.find_element_by_xpath('//li[@class="messageli"]//div[contains(@class,"message") and contains(@class,"default")]')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download