Python的硒:查找h1元素,但返回空字符串
问题描述:
我试图让在标题的文本对这个page:Python的硒:查找h1元素,但返回空字符串
的iShares FTSE MIB UCITS ETF欧元(DIST)
标签看起来是这样的:
<h1 class="product-title" title="iShares FTSE MIB UCITS ETF EUR (Dist)"> iShares FTSE MIB UCITS ETF EUR (Dist) </h1>
我使用这个XPath:通过.text
在硒的webdriver
xp_name = ".//*[@class[contains(normalize-space(.), 'product-title')]]"
检索的Python:
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
检查更新的答案与问题的说明 – Andersson