我正在尝试使用R解析html文档。有一个我想抓取的节点,但是在该节点内有一些我不需要的信息。

例如:

<div class="content">
 <h3>Titel</h3>
 <p>content</p>
 <p>content</p>
 <ul>
  <li>List</li>
  <li>List</li>
 </ul>
</div>


我需要所有内容以及列表。我不需要标题。所以通常我会用下面的代码来抓它:

grabIt <- xml_text(xml_find_all(html, xpath="//div[@class='content']//text()
                       [not(ancestor-or-self::div[@class='content']//h3)]"))


这通常可以正常工作。但是这里的“ [not(ancestor-or-self-”)行过滤掉了所有内容。我认为这是因为我正在过滤要捕获的节点中的某些内容。代码在那些标题正确的情况下可以正常工作或我不需要的任何其他信息在这样的单独节点中:

<div class="content">
 <div class="Titel">Title</div>  #difference
 <p>content</p>
 <p>content</p>
 <ul>
  <li>List</li>
  <li>List</li>
 </ul>
</div>


我得到的另一个想法是:

grabIt <- xml_text(xml_find_all(html, xpath="//div[@class='content']//p//text()"))


但是问题是,我无法同时获取该段落和列表。

最佳答案

试试这个xpath:

//div[@class='content']/*[not(name()='h3')][name()='p']/text() | //div[@class='content']/*[not(name()='h3')]/*[name()='li']/text()

它给 :

'content'
'content'
'List'
'List'

关于r - R:使用xpath过滤节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38596577/

10-12 13:01
查看更多