如何在两个节点之间提取文本内容

我要提取红色和绿色矩形中包含的文本,如下面的屏幕截图所示, N.B:文本不包含在开始和结束标记中

http://temperate.theferns.info/plant/Acacia+omalophylla

如何在两个节点之间提取文本内容

例如,对于绿色矩形的文本,我测试了此xpath查询和以下代码(python / selenium):

greenrec_xpath = "//*[preceding::h3[contains(text(),'General Information')] and following::h3[contains(text(),'Known Hazards')]]"
driver.find_elements_by_xpath(greenrec_xpath)

但没有预期的结果

任何想法!

thinkphilo 回答:如何在两个节点之间提取文本内容

当文本周围没有直接的括号时,它被称为文本节点,并且由于无法像您尝试的那样直接访问而难以查找。我通常要做的是找到直接父级的位置,并从中获取文本。如果该父节点下有多个文本节点,则将变得有些棘手,并且在获取整个文本后通常需要进行一些解析/拆分。

或者,如果您可以保证自己的文本节点包含某些特定文本,则可以将curl "http://0.0.0.0:5001/event/email/?event_type=open&email_type=questions"text()交换,并以此方式创建xpath。例如: .

,
greenrec_xpath = 
 "//*[preceding::h3[contains(text(),'General Information')] 
    and following::h3[contains(text(),'Known Hazards')]]"

您几乎可以找到选择所需文本节点的XPath表达式:

使用

//*[preceding::h3[1][contains(.,'General Information')] 
  and following::h3[1][contains(.,'Known Hazards')]
   ]/text()[normalize-space()]

请注意,此表达式选择了许多文本节点(在这种情况下为5)。

如果要获取单个字符串,则需要获取每个选定文本节点的字符串值,并将它们串联在一起成为单个字符串。如果只能使用XPath 1.0,则需要在调用程序代码(非XPath)中执行此字符串连接。

如果可以使用XPath 2.0(或更高版本),请使用

string-join(
            //*[preceding::h3[1][contains(.,'General Information')] 
              and following::h3[1][contains(.,'Known Hazards')]
               ]/text()[normalize-space()]/string(.),''
           )
,

要提取相思属的文本分类... ,因为该元素是文本节点,您需要为visibility_of_element_located()引入 WebDriverWait 可以使用以下Locator Strategy

  • 代码块:

    driver.get("http://temperate.theferns.info/plant/Acacia+omalophylla")
    print(driver.execute_script('return arguments[0].childNodes[11].textContent;',WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"div.PageBox")))).strip())
    
  • 控制台输出:

    Classification of the genus Acacia (in the wider sense) has been subject to considerable debate. It is generally agreed that there are valid reasons for breaking it up into several distinct genera,but there has been disagreement over the way this should be done. As of 2017,it is widely (but not completely) accepted that the section that includes the majority of the Australian species (including this one) should retain the name Acacia,whilst other sections of the genus should be transferred to the genera Acaciella,Mariosousa,Senegalia and Vachellia[
    
本文链接:https://www.f2er.com/3063669.html

大家都在问