Python Selenium:找到 h1 元素但 returns 空文本字符串

Python Selenium: Finds h1 element but returns empty text string

我正在尝试获取 header 中关于此 page 的文本:

iShares FTSE MIB UCITS ETF EUR (Dist)

标签如下所示:

<h1 class="product-title" title="iShares FTSE MIB UCITS ETF EUR (Dist)"> iShares FTSE MIB UCITS ETF EUR (Dist) </h1>

我正在使用这个 xPath:

xp_name = ".//*[@class[contains(normalize-space(.), 'product-title')]]"

在 Selenium WebDriver 中通过 .text 检索 Python:

new_name = driver.find_element_by_xpath(xp_name).text

driver 找到 xpath,但是当我打印 new_name 时,macOS 终端只打印一个空字符串:""

这可能是什么原因?


注意:我还尝试了其他一些 xpath 替代方案,得到了相同的结果,例如:

xp_name = ".//*[@id='fundHeader']//h1"

问题是有两个 h1 元素具有完全相同的外部 HTML:第一个是隐藏的,第二个不是。您可以使用

查看
print(len(driver.find_elements_by_xpath('//h1[@class="product-title "]')))

text 属性 允许您从 仅可见的 元素获取文本,而 textContent 属性还允许获取 [=28] 的文本=]隐藏一个

尝试替换

new_name = driver.find_element_by_xpath(xp_name).text

new_name = driver.find_element_by_xpath(xp_name).get_attribute('textContent')

或者简单地处理第二个(可见)header:

driver.find_elements_by_xpath('//h1[@class="product-title "]')[1].text

正如@ahmad-moussa 提到的,对我来说解决方案是:

import time

(...)

time.sleep(1)
# before 
<webelement>.text