簡體   English   中英

如何使用 selenium 為 python 獲取跨度標記文本

[英]How to get span tag text with selenium for python

使用下面的 html 代碼,我想獲取 div 標簽內第三個 span 標簽的值。 例如,當我點擊 id psr2 時,我想檢索值“aaaa, bbbb”。

我寫了這段代碼:

    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)

html代碼:

<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>

你能幫我找到用戶名嗎?

最好的祝福

使用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)

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)

更新。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM