You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium使用find_element获取分页文本无输出问题排查

问题:Selenium获取分页元素文本无输出

我尝试定位分页数字以实现循环遍历,需要获取该元素的文本内容,但执行以下代码后终端无任何输出:

print(driver.find_element("xpath", "//div[@class='pagination']/span[@class='pagination-compteur']").text)

对应的HTML代码:

<div class="pagination">
<span class="disabled previous ">
<span class="icon-lt-arrow-left"></span>
<span class="value">Précédent</span>
</span>
<span id="SEL-compteur" class="pagination-compteur"><strong>Page 1</strong> / 3</span>
<a class="link_pagination next pj-lb pj-link" id="pagination-next" title="Page suivante" href="#" data-pjlb="{&quot;url&quot;:&quot;L3BhZ2VzYmxhbmNoZXMvcmVjaGVyY2hlP3F1b2lxdWk9c3lsdmllJm91PUl2cnklMjBzdXIlMjBTZWluZSUyMCUyODk0MjAwJTI5JmlkT3U9TDA5NDA0MTAwJnF1b2lRdWlJbnRlcnByZXRlPXN5bHZpZSZjb250ZXh0ZT04OEhSaFRSdUNXeTBrJTJCWkhUTjdrVlF4SVNNUm5kTkZzVFg4UGclMkJ5bDBpRSUzRCZwYWdlPTI=&quot;,&quot;ucod&quot;:&quot;b64u8&quot;}" data-pjstats="{&quot;idTag&quot;:&quot;PAGE-SUIV&quot;,&quot;pjscript&quot;:&quot;pa.sendEvent('click.navigation',{'click_chapter1':'LEGACY_CLIC','click_chapter2':'MAPPING_CLIC_LR','click':'PAGE_SUIV',idtag:'{%nom}',site_level2:xtn2});&quot;}"> <span class="value">Suivant</span>
<span class="icon icon-lt-arrow-right"></span>
</a>
</div>

解决方法

1. 等待元素完全加载

页面可能未完成渲染就执行了定位代码,导致无法获取文本。用显式等待确保元素可见:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待10秒,直到元素可见
compteur_element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.XPATH, "//div[@class='pagination']/span[@class='pagination-compteur']"))
)
print(compteur_element.text)

2. 换用更可靠的定位器

目标元素有唯一ID SEL-compteur,直接用ID定位比XPath更稳定:

print(driver.find_element(By.ID, "SEL-compteur").text)

3. 尝试获取内部文本属性

如果元素本身不可见但实际存在,.text可能返回空,改用textContent或innerText属性:

element = driver.find_element(By.ID, "SEL-compteur")
print(element.get_attribute("textContent"))  # 或 element.get_attribute("innerText")

4. 检查是否在iframe中

如果分页元素嵌套在iframe里,需要先切换到iframe再定位:

# 找到iframe并切换
iframe = driver.find_element(By.TAG_NAME, "iframe")
driver.switch_to.frame(iframe)

# 执行定位代码
print(driver.find_element(By.ID, "SEL-compteur").text)

# 操作完成后切回主文档
driver.switch_to.default_content()

内容的提问来源于stack exchange,提问作者kévin Goncalves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 22:52:27