【问题标题】:rvest: xpath get text at current node with sub nodes removedrvest:xpath 在当前节点获取文本,删除子节点
【发布时间】:2018-02-09 02:05:02
【问题描述】:

我有一些文本嵌套在我想要抓取的 div 标记中。特别是下面 MWE 的地址 (Hillsgrove, Missouri 13231-1123)。在这个 div 标签内部是我希望忽略的其他标签。我想在第一个<br /> 之后只获取当前 div 标签处的文本。至少我想取回没有其他子节点文本的字幕+地址,但理想情况下我只想要地址文本。

我正在使用 R 的 rvest 包来完成这项任务,但似乎这是一个更一般的 xpath 问题。

MWE

library(xml2); library(rvest); library(dplyr)

minimal <- read_html(
"<!doctype html>
<meta charset=utf-8>
<title>blah</title>
<div class=\"span4\"> 
    <a href='http://www.stuff.com'>
        <strong>Sub Title</strong>
     </a>
  <br />
  Hillsgrove, Missouri 13231-1123<br />
  <span id=\"phone\">(5555) 555-5555</span><br />
  <a target=\"_blank\" href='http://www.morestuff.com'>www.morestuff.com</a>
  <br /><br />
</div>"
)

minimal %>%
    html_nodes(xpath = '//div[@class="span4"]') %>%
    html_text() 

## [1] " \n    \n        Sub Title\n     \n  \n  Hillsgrove, Missouri 13231-1123(5555) 555-5555www.morestuff.com\n  "

期望的结果

## Hillsgrove, Missouri 13231-1123

我愿意接受

## " \n    \n        Sub Title\n     \n  \n  Hillsgrove, Missouri 13231-1123"

【问题讨论】:

    标签: r xpath rvest


    【解决方案1】:

    如果你想要当前节点的文本节点,使用text()

    minimal %>%
      html_nodes(xpath = '//div[@class="span4"]/text()') %>%
      html_text() 
    # [1] " \n  "                               "\n  "                               
    # [3] "\n  Hillsgrove, Missouri 13231-1123" "\n  "
    

    你能看到它确实返回了换行符和空格,但应该很容易去掉。

    【讨论】:

    • 太棒了...不知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多