Reputation: 147
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" class="treeNode">
<nobr>
<a class="focusableNode" href="#r2" onclick="return false;" tabindex="0" onkeydown="ps.onKeyDown(this);">
<span role="presentation">
<span id="countLabel" class="hidden-label">Elément de liste 3 sur {5}</span>
<span>aaaa, bbbb</span>
<label name="SelectInfo" class="hidden-label"></label>
</span>
</a>
</nobr>
</div>
<div id="psr3" uid="6653" class="treeNode">
<nobr>
<a class="focusableNode" href="#r3" onclick="return false;" tabindex="0" onkeydown="ps.onKeyDown(this);">
<span role="presentation">
<span id="countLabel" class="hidden-label">Elément de liste 4 sur {5}</span>
<span>xxxx, yyyy</span>
<label name="SelectInfo" class="hidden-label"></label>
</span>
</a>
</nobr>
</div>
Could you, please, help me to find the userName ?
Best regards
Upvotes: 1
Views: 97
Reputation: 33384
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)
Upvotes: 1