deepakbhavale67
deepakbhavale67

Reputation: 347

How to locate the element and extract the innerText using Selenium and Python

<span class="chr-UserDropdownItem-imageAndText">
    <img class="chr-UserDropdownItem-image" src="/slm/profile/image/264023573852/24.sp?version=1" alt="User Profile Avatar">
    <span class="smb-DropdownItem-text">
        <span>   test user   </span>
    </span>
</span>

By taking look on above screenshot please help me extract the innerText test user uniquely from span tag.

Upvotes: 1

Views: 3402

Answers (4)

Udhav Sarvaiya
Udhav Sarvaiya

Reputation: 10101

You can use XPath like this for remove white-space:

driver.find_element_by_xpath('//span/text()[normalize-space()="test user"]')

If you don't have white-space in the span tag, use XPath this way:

driver.find_element_by_xpath('//span[contains(text(), "test user")]')

For Dynamically:

driver.find_element_by_xpath('//span[contains(text(), "' . $HereIsSetYourDynamicallyVaribleName . '")]')

Upvotes: 1

Muzzamil
Muzzamil

Reputation: 2881

You can give it try with below xpath.

//img[contains(@src, '/profile/image/')]]/following-sibling::span

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193298

To extract the text test user you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and get_attribute():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.smb-DropdownItem-text>span"))).get_attribute("innerHTML"))
    
  • Using XPATH and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "span[@class='smb-DropdownItem-text']>span"))).text)
    
  • 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
    

Upvotes: 1

Sameer Arora
Sameer Arora

Reputation: 4507

You can find the element using the xpath:

driver.find_element_by_xpath("//span[@class='smb-DropdownItem-text']//span[contains(text(),'test user')]");

Upvotes: 0

Related Questions