Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 刮削中的等效物是什么?_R_Rvest - Fatal编程技术网

R 刮削中的等效物是什么?

R 刮削中的等效物是什么?,r,rvest,R,Rvest,我正在尝试运行一些刮取操作,其中对节点执行的操作取决于节点的内容 这应该是一个简单的例子: XML = '<td class="id-tag"> <span title="Really Long Text">Really L...</span> </td> <td class="id-tag">Short</td>' page = read_html(XML) 执行第二步的代码是: page %>% htm

我正在尝试运行一些刮取操作,其中对节点执行的操作取决于节点的内容

这应该是一个简单的例子:

XML =
'<td class="id-tag">
    <span title="Really Long Text">Really L...</span>
</td>
<td class="id-tag">Short</td>'

page = read_html(XML)
执行第二步的代码是:

page %>% html_nodes(xpath = '//td[@class="id-tag"]') %>% html_text
# [1] "\n    Really L...\n" "Short"  
真正的问题是
html\u attr
方法没有为不匹配的节点提供任何
NA
或类似的内容(即使我让
xpath
只是
”//td[@class=“id tag”]“
首先要确定的是,我已经缩小到只包含相关的节点。这会破坏顺序——我无法自动判断原始结构在第一个节点还是第二个节点上有
“非常长的文本”

(我想做一个连接,但是缩写文本和全文之间的映射不是一对一/可逆的)

似乎在正确的路径上--
xpath
中的if/else构造--但不起作用

理想情况下,我会得到输出:

# [1] "Really Long Text" "Short" 
基于此,您可以执行以下操作

page %>% 
   html_nodes(xpath='//td[@class="id-tag"]') %>% 
   {ifelse(is.na(html_node(.,xpath="span")), 
           html_text(.),
           {html_node(.,xpath="span") %>% html_attr("title")}
   )}
我认为丢弃管道并保存沿途创建的一些对象可能很简单

nodes <- html_nodes(page, xpath='//td[@class="id-tag"]')
text <- html_text(nodes)
title <- html_attr(html_node(nodes,xpath='span'),"title")
value <- ifelse(is.na(html_node(nodes, xpath="span")), text ,title)
另一种方法:

library(tidyverse)
library(rvest)

XML <- '
<td class="id-tag">
    <span title="Really Long Text">Really L...</span>
</td>
<td class="id-tag">Short</td>
'

pg <- read_html(XML)

html_nodes(pg, "td[class='id-tag']") %>%
  map_chr(function(x) {
    if (xml_find_first(x, "boolean(.//span)")) {
      x <- html_nodes(x, xpath=".//span/@title")
    }
    html_text(x)
  })

## [1] "Really Long Text" "Short"
库(tidyverse)
图书馆(rvest)

XML我认为对于没有匹配的分支,
html\u节点
返回
NA
这一事实是我在这里最需要的,谢谢!而且这个联合
xpath
是一个野兽!你能详细说明
[不是(.//span)]
位在做什么吗?我主要不了解周围的
[]
,我想?@MichaelChirico,它是基于,没有包装
[]
您会得到一个语法错误(此部分正在查找带有class=id标记但没有子节点“span”的节点td)
page %>% 
 html_nodes(xpath='//td[@class="id-tag"]/span/@title|//td[@class="id-tag"][not(.//span)]') %>%
 html_text()
library(tidyverse)
library(rvest)

XML <- '
<td class="id-tag">
    <span title="Really Long Text">Really L...</span>
</td>
<td class="id-tag">Short</td>
'

pg <- read_html(XML)

html_nodes(pg, "td[class='id-tag']") %>%
  map_chr(function(x) {
    if (xml_find_first(x, "boolean(.//span)")) {
      x <- html_nodes(x, xpath=".//span/@title")
    }
    html_text(x)
  })

## [1] "Really Long Text" "Short"