草庐IT

python Selenium : Finds h1 element but returns empty text string

coder 2023-08-19 原文

我正在尝试获取此 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 for Python 中通过 .text 检索:

new_name = driver.find_element_by_xpath(xp_name).text

驱动程序找到了 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 属性还允许获取隐藏元素

尝试替换

new_name = driver.find_element_by_xpath(xp_name).text

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

或者简单地处理第二个(可见的)标题:

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

关于 python Selenium : Finds h1 element but returns empty text string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429788/

有关python Selenium : Finds h1 element but returns empty text string的更多相关文章

随机推荐