【问题标题】:Can I access the subchild of a parent in XPath?我可以在 XPath 中访问父级的子子级吗?
【发布时间】:2015-06-30 16:12:41
【问题描述】:

因此,正如标题所述,我有一些来自 http://chem.sis.nlm.nih.gov/chemidplus/name/acetone 的 HTML 代码,我正在解析这些代码,并希望从我的类似帖子 How to set up XPath query for HTML parsing? 中提取一些数据,例如 MeSH 标题下的丙酮

<div id="names">
 <h2>Names and Synonyms</h2>
  <div class="ds">
   <button class="toggle1Col" title="Toggle display between 1 column of wider results and multiple columns.">&#8596;</button>
 <h3>Name of Substance</h3>
 <div class="yui3-g-r">
  <div class="yui3-u-1-4">
   <ul>
    <li id="ds2">
     <div>2-Propanone</div>
    </li>
   </ul>
  </div>
  <div class="yui3-u-1-4">
   <ul>
    <li id="ds3">
     <div>Acetone</div>
    </li>
   </ul>
  </div>
  <div class="yui3-u-1-4">
   <ul>
    <li id="ds4">
     <div>Acetone [NF]</div>
    </li>
   </ul>
  </div>
  <div class="yui3-u-1-4">
   <ul>
    <li id="ds5">
     <div>Dimethyl ketone</div>
    </li>
   </ul>
  </div>
 </div>
 <h3>MeSH Heading</h3>
  <ul>
   <li id="ds6">
    <div>Acetone</div>
   </li>
  </ul>
 </div>
</div>

以前在其他页面中我会使用mesh_name = tree.xpath('//*[text()="MeSH Heading"]/..//div')[1].text_content() 来提取数据,因为其他页面具有相似的结构,但现在我发现情况并非如此,因为我没有考虑不一致。那么,有没有办法在转到我想要的节点然后获取它的子节点之后,允许不同页面之间的一致性?

tree.xpath('//*[text()="MeSH Heading"]//preceding-sibling::text()[1]') 会起作用吗?

【问题讨论】:

    标签: python html xpath lxml lxml.html


    【解决方案1】:

    据我了解,您需要通过标题获取项目列表。

    如何制作一个适用于“名称和同义词”容器中每个标题的可重用函数:

    from lxml.html import parse
    
    
    tree = parse("http://chem.sis.nlm.nih.gov/chemidplus/name/acetone")
    
    def get_contents_by_title(tree, title):
        return tree.xpath("//h3[. = '%s']/following-sibling::*[1]//div/text()" % title)
    
    print get_contents_by_title(tree, "Name of Substance")
    print get_contents_by_title(tree, "MeSH Heading")
    

    打印:

    ['2-Propanone', 'Acetone', 'Acetone [NF]', 'Dimethyl ketone']
    ['Acetone']
    

    【讨论】:

    • 啊,你是对的,我忘记了函数。虽然你能解释一下函数的 xpath 语法吗?
    • @TimTom 当然,在这里我们通过文本定位h3,获取下一个following-sibling 并提取该兄弟中任何位置的所有div 元素的文本。希望这能让事情变得更清楚。
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 2017-06-09
    • 2014-07-13
    • 2018-06-14
    • 2017-04-20
    • 2021-10-20
    • 1970-01-01
    • 2021-11-18
    相关资源
    最近更新 更多