我是Selenium的初学者,但是我设法掌握了一些基础知识。问题是我有一个div标记,其中包含一些文本,但无法从中获取文本。我应该补充一点,我正在使用Python。
相关站点上的标签本身如下:
<div class="xtb-text" id="ext-comp-1223">Displaying 1 - 25 of 184</div>
我想要的文字是“显示1-25(共184)”,但我似乎无法理解。
我复制了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几次,而且我确定它是我所追求的。毕竟,文本就在标签中。但是我似乎无法理解。
我在做什么错了?
答案 0 :(得分:0)
回答我自己的问题:
该元素位于动态生成的表中。由于加载该表需要花费几秒钟的时间,因此在我访问该表时未填充div标签。但是,当我稍后检查这些元素以查看我做错了什么时,当然会填充它。
作为解决此问题的一种临时方法,只需在这些打印品显示可以访问的信息之前添加几秒钟的睡眠即可。
答案 1 :(得分:0)
确保使用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
,请尝试将类与其他组合一起使用。