Python Selenium:查找h1元素,但返回空文本字符串
问题内容:
我试图让这个在标题的文本页面:
iShares富时MIB UCITS ETF欧元(距离)
标签看起来像这样:
<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')]]"
通过.text
Selenium WebDriver for Python检索:
new_name = driver.find_element_by_xpath(xp_name).text
驱动程序找到了xpath,但是当我打印时new_name
,macOS Terminal只打印一个空白字符串:""
这可能是什么原因?
注意:我还尝试了其他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