我是Selenium的新手,我一直有一个问题,我试图提取标题 "铁麦芽酚 "作为字符串,在这里。
https:/meshb.nlm.nih.govrecordui?ui=C062088。
但我一直有很多麻烦。
在Python中使用xpath,进行了几次不同的尝试,但都没有成功。
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]。它应该是一个元素。
to_store=driver.find_elements_by_xpath('/html/body/div[2]/h1/text()').text
*** selenium.common.exceptions.InvalidSelectorException: 消息:无效选择器。xpath表达式 "htmlbodydiv[2]h1text() "的结果是:[对象Text]。对象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]。应该是一个元素。
有谁有线索吗?
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())
产量。
麦芽酚铁
由于您的 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
属性的值。