Selenium Python 无法提取 [对象 Text] 它应该是一个元素。

问题描述 投票:0回答:1

我是Selenium的新手,我一直有一个问题,我试图提取标题 "铁麦芽酚 "作为字符串,在这里。

https:/meshb.nlm.nih.govrecordui?ui=C062088。

但我一直有很多麻烦。

在Python中使用xpath,进行了几次不同的尝试,但都没有成功。

  1. 第一次尝试
to_store=driver.find_elements_by_xpath('/html/body/div[2]/h1/text()').get_attribute('textContent')

*** selenium.common.exceptions.InvalidSelectorException: 消息:无效选择器。xpath表达式 "htmlbodydiv[2]h1text() "的结果是:[对象Text]。对象Text]。它应该是一个元素。

  1. 第二次尝试
to_store=driver.find_elements_by_xpath('/html/body/div[2]/h1/text()').text

*** selenium.common.exceptions.InvalidSelectorException: 消息:无效选择器。xpath表达式 "htmlbodydiv[2]h1text() "的结果是:[对象Text]。对象Text]。它应该是一个元素。

  1. 第三次尝试:在 "htmlbodydiv[2]h1text("的xpath表达式结果是:[对象Text]。
to_store=driver.find_elements_by_xpath('/html/body/div[2]/h1/text()').get_attribute('outerHTML')

selenium.common.exceptions.InvalidSelectorException。消息:无效的选择器。xpath表达式 "htmlbodydiv[2]h1text() "的结果是:[对象Text]。对象Text]。应该是一个元素。

有谁有线索吗?

python selenium xpath
1个回答
0
投票

Selenium不允许你使用Text节点定位一个元素。作为一个替代方案,你可以使用下面的javascript代码来提取文本。

element = driver.find_element_by_css_selector('h1.ng-binding.ng-scope')
text = driver.execute_script("return arguments[0].childNodes[0].textContent", element);
print(text.strip())

产量。

麦芽酚铁


0
投票

由于您的 XPath 表达式以 text() 结束,这将解析为一个文本容器,而不是一个 HTML 元素(或 list of)。因此,你会得到上述错误。

driver = webdriver.Chrome('../chromedriver.exe') #set your path here
driver.get("https://meshb.nlm.nih.gov/record/ui?ui=C062088")
driver.set_page_load_timeout(45)
driver.implicitly_wait(2)
SpecialPrice=driver.find_element_by_xpath("/html/body/div[2]/div/div/div[1]/div/dl/dd[1]").text
print(SpecialPrice)

输出

ferric maltol

使用上面的方法,你将完整的 xpath 并使用 text 属性的值。

© www.soinside.com 2019 - 2024. All rights reserved.