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

2024-04-26 09:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

enter image description here

例如,对于绿色矩形的文本,我测试了这个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)

但没有达到预期的效果

任何想法!你知道吗


Tags: text标记文本infohttp屏幕xpathh3
3条回答

当文本周围没有直接包围的括号时,它被称为文本节点,查找起来有点困难,因为它不能像您尝试的那样直接访问。我通常要做的是找到直接父母的位置,并从中获取文本。如果父节点下有多个文本节点,并且在获取整个文本后通常需要进行一些解析/拆分,那么这就变得有点棘手了。你知道吗

或者,如果您可以保证您的文本节点包含一些特定的文本,那么您可以将text().交换,并使xpath成为这样。例如: //*[contains(.,'Acacia omalophylla')]

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)。你知道吗

如果要获取单个字符串,则需要获取每个选定文本节点的字符串值,并将这些值串联在单个字符串中。如果只能使用XPath1.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[
    

相关问题 更多 >