Home > Software design >  How to get span tag text with selenium for python
How to get span tag text with selenium for python

Time:10-11

With the html code below, I want to get the value of the third span tag inside the div tag. For example when I clicked on the id psr2, I want to retrieve the value 'aaaa, bbbb'.

I have written this code :

    n = randint(0,9)
    userPos = 'psr' str(n)
    WebDriverWait(browser, maxTimeout).until(EC.element_to_be_clickable((By.ID, str(userPos)))).click()
    userName = WebDriverWait(browser, maxTimeout).until(EC.visibility_of_element_located((By.ID, "countLabel")[n])).text
    print(userName)

The html code :

<div id="psr2" uid="19202" >
  <nobr>
    <a  href="#r2" onclick="return false;" tabindex="0" onkeydown="ps.onKeyDown(this);">
      <span role="presentation">
        <span id="countLabel" >Elément de liste 3 sur {5}</span>
        <span>aaaa, bbbb</span>
        <label name="SelectInfo" ></label>
      </span>
    </a>
  </nobr>
</div>


<div id="psr3" uid="6653" >
  <nobr>
    <a  href="#r3" onclick="return false;" tabindex="0" onkeydown="ps.onKeyDown(this);">
      <span role="presentation">
        <span id="countLabel" >Elément de liste 4 sur {5}</span>
        <span>xxxx, yyyy</span>
        <label name="SelectInfo" ></label>
      </span>
    </a>
  </nobr>
</div>

Could you, please, help me to find the userName ?

Best regards

CodePudding user response:

Use following-sibling xpath

n = randint(0,9)
userPos = 'psr' str(n)
WebDriverWait(browser, maxTimeout).until(EC.element_to_be_clickable((By.ID, str(userPos)))).click()
userName = WebDriverWait(browser, maxTimeout).until(EC.visibility_of_element_located((By.XAPTH, "//span[@id='countLabel']/following-sibling::span"))).text
print(userName)

or following

n = randint(0,9)
userPos = 'psr' str(n)
WebDriverWait(browser, maxTimeout).until(EC.element_to_be_clickable((By.ID, str(userPos)))).click()
userName = WebDriverWait(browser, maxTimeout).until(EC.visibility_of_element_located((By.XAPTH, "//span[@id='countLabel']/following::span[1]"))).text
print(userName)

Update.

n = randint(0,9)
userPos = 'psr' str(n)
WebDriverWait(browser, maxTimeout).until(EC.element_to_be_clickable((By.ID, str(userPos)))).click()
xpath="//div[@id='{}']//span[@id='countLabel']/following-sibling::span".format(userPos)
userName = WebDriverWait(browser, maxTimeout).until(EC.visibility_of_element_located((By.XAPTH,xpath))).text
print(userName)
userName = WebDriverWait(browser, maxTimeout).until(EC.visibility_of_element_located((By.XAPTH,xpath))).get_attribute(textContent)
print(userName)
  • Related