0

I don't know if this is often asked but I just can't figure out how to get the text info of an span bracket in the html code using python with selenium.

For example following code:

<li class="addetailslist--detail">
area
<span class="addetailslist--detail--value">
72,05 m²
</span>
</li>

<li class="addetailslist--detail">
rooms
<span class="addetailslist--detail--value">
2,5
</span>
</li>

Since I have multiple elements of "addetailslist--detail" on the page, I want to address them by using the words "area" or "rooms". Then I want to get the specific text from the class "addetailslist--detail--value" (e.g. 72,05m² and 2,5). I just can't figure out, how to address them the proper way. Can someone quickly help me on that one?

This is how far I have come:

area = self.browser.find_element_by_xpath("//*[contains(text(), 'area')]")

But this just delievers the whole element...

LaBa
  • 1
  • 1

1 Answers1

0

To extract the texts e.g. 72,05 m² and 2,5 from all of the <span> using Selenium and you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and get_attribute("innerHTML"):

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(self.browser, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.addetailslist--detail span.addetailslist--detail--value")))])
    
  • Using XPATH and text attribute:

    print([my_elem.text for my_elem in WebDriverWait(self.browser, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='addetailslist--detail']/span[@class='addetailslist--detail--value']")))])
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Hi DebanjanB, thanks for your reply! So far so good, but can you also tell me how to get the associated texts to a specific value? For example, when I just want to get the 72,05m² for the keyword "area"? – LaBa Dec 20 '20 at 23:26
  • @LaBa Sounds like a different question all together. Can you raise a new question please? – undetected Selenium Dec 21 '20 at 07:25
  • Technically, I did it in this question. "Since I have multiple elements of "addetailslist--detail" on the page, I want to address them by using the words "area" or "rooms"." – LaBa Dec 21 '20 at 11:45