Selenium访问div标记中的文本

2024-06-02 07:40:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Selenium有点初级,但我已经掌握了一些基础知识。问题是我有一个div标签,里面有一些文本,我无法从中提取文本。我应该补充一点,我正在使用Python

有关站点上的标签本身如下所示:

<div class="xtb-text" id="ext-comp-1223">Displaying 1 - 25 of 184</div>

我想要的文本是“显示184中的1-25”,但我似乎无法得到它

我复制了div标记的XPath,如下所示:

//*[@id="ext-comp-1223"]

我用这个来获取元素。我尝试了.text方法,但没有得到文本。事实上,我尝试了我在网上看到的每一个访问者,只是想看看他们中的一些是否提供了有意义的信息。详情如下:

print('Details for Display page info 1: ---')
    print(self.DisplayPageInfo.element.text)
    print(self.DisplayPageInfo.element.tag_name)
    print(self.DisplayPageInfo.element.parent)
    print(self.DisplayPageInfo.element.location)
    print(self.DisplayPageInfo.element.size)

    print('Details for Display page info 2: ---')
    print(self.DisplayPageInfo.element.get_attribute('text'))
    print(self.DisplayPageInfo.element.get_attribute('tag_name'))
    print(self.DisplayPageInfo.element.get_attribute('parent'))
    print(self.DisplayPageInfo.element.get_attribute('location'))
    print(self.DisplayPageInfo.element.get_attribute('size'))
    print(self.DisplayPageInfo.element.get_attribute('value'))
    print(self.DisplayPageInfo.element.get_attribute('innerText'))
    print(self.DisplayPageInfo.element.get_attribute('textContent'))

结果如下:

Details for Display page info 1: ---
No data to display
div
<selenium.webdriver.chrome.webdriver.WebDriver (session="a050377decd1cdc7fb98e80f91d8b9af")>
{'x': 1274, 'y': 646}
{'height': 18, 'width': 93}
Details for Display page info 2: ---
None
None
None
None
None
None
No data to display
No data to display

我也尝试了element.innerText和element.value,但是这些属性对于web元素来说并不存在,所以代码抛出了一个异常

我已经多次检查了XPath,我确信它就是我要找的那个。毕竟,文本就在标签上。但我就是不明白

我做错了什么


Tags: text文本selfdivinfononeforget
2条回答

确保使用explicit wait而不是硬编码睡眠explicit wait将在满足条件时继续执行后续步骤(在您的情况下,div元素存在),而sleep则会在div存在后等待给定的时间

下面是如何使用显式等待的代码段

# make sure to add below improts
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

# Here is the line that will make sure the script waits for the element to present

DisplayPageInfo = (wait.until(EC.presence_of_element_located((By.xpath, locator))))

如果元素具有dynamic id,请尝试将该类与其他组合使用

回答我自己的问题:

元素位于动态生成的表中。因为加载该表需要几秒钟,所以在我访问它时没有填充div标记。但是当我稍后检查元素以查看我做错了什么时,它当然被填充了

作为一种临时修复方法,只需在这些打印显示信息可以访问之前添加几秒钟的睡眠

相关问题 更多 >