python - 从 xpath 中的多个子节点中选择文本

标签 python xpath

我需要在 Python 2.6 中使用 XPath 和 lxml 来提取两个文本项:

-名称一种类型1描述1

-名称两个类型 2 描述 2

我尝试使用以下 Xpath: '//*[@id="results"]/li/div/p/child::text()' 然而,这只给了我以下文本

-命名一种类型 1

-命名两种类型 2

关于正确使用 Xpath 有什么建议吗?

<div id="container">
  <ol id="results">
   <li class="mod1" data-li-position="0">
    <a href="first.link"><img src="image001.jpg"></a>
    <div class="bd">
     <h3>
      <a href="some.link">Category 1</a>
     </h3>
     <p class="description">
       <strong class="highlight">Name One</strong>
       <strong class="highlight">Type 1</strong>
       Description 1
     </p>
    </div>
   </li>
   <li class="mod2" data-li-position="1">
    <a href="second.link"><img src="image002.jpg"></a>
    <div class="bd">
     <h3>
      <a href="another.link">Category 2</a>
     </h3>
     <p class="description">
       <strong class="highlight">Name Two</strong>
       Description 2
       <strong class="highlight">Type 2</strong>
     </p>
    </div>
   </li>

最佳答案

XPath 的最后一部分:

...../p/child::text()

...仅选择 <p>子节点的文本节点。这就是为什么您错过了,例如 Description 1 ,因为它是 <p>直接子。您可以尝试将该部分更改为如下:

...../p//text()

上面的 XPath 将选择 <p>后代所有文本节点,换句话说,<p> 内任何位置的所有文本节点。

关于python - 从 xpath 中的多个子节点中选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26687119/

相关文章:

python - __del__ 在程序结束时

Meta Open Graph xpath 选择器的 Python Selenium 问题

xml - 如何使用 XQuery 提取特定的 XML 记录并以逗号分隔格式输出?

sql - 在部分xpath上的Oracle 10.2.0.4.0查询

Python 通过 xml 抓取打印空括号

Python导入

python - Pandas 在数据框中丢弃单词

python - Matplotlib 均匀分布的轮廓线

指定兼容解释器版本的 Python 约定?

xslt - XSL:如何最好地将节点存储在变量中,然后在以后的xpath表达式中使用它?