2

给定以下示例:

sites=c('site 1','site 2')
link=c('<a href="http://example.com/path">This website</a>', '<a href="http://example.com/path2">That website</a>')
w=data.frame(link,sites)
w
                                             link      sites
<a href="http://example.com/path">This website</a>   site 1
<a href="http://example.com/path2">That website</a>  site 2

如何应用将解析 html 片段以提取 url 和链接文本并将它们弹出到数据框中的单独列中的正则表达式?因此,例如,给定上面的示例,我需要做什么才能生成如下所示的数据框:

                     url          name     sites
http://example.com/path    This website   site 1
http://example.com/path2   That website   site 2
4

2 回答 2

8

这是使用包中的htmlTreeParse函数的解决方案XML(即,没有正则表达式)

R> library("XML") 
R> htp <- htmlTreeParse(link)
R> t(sapply(seq_along(link),
+           function(i) c(url=unname(htp$children$html[[1]][[i]]$attributes),
+                         name=htp$children$html[[1]][[i]]$children$text$value,
+                         sites=sites[i])))
     url                        name           sites   
[1,] "http://example.com/path"  "This website" "site 1"
[2,] "http://example.com/path2" "That website" "site 2"
于 2011-09-02T09:34:42.240 回答
0

替代解决方案rvest

library(rvest)

sites <- c('site 1','site 2')
link <- c('<a href="http://example.com/path">This website</a>', 
          '<a href="http://example.com/path2">That website</a>')
w <- data.frame(link, sites)

anchors <- html_nodes(read_html(paste0(w$link, collapse="")), "a")

data.frame(url=html_attr(anchors, "href"),
           name=html_text(anchors),
           sites=w$sites)
##                        url         name  sites
## 1  http://example.com/path This website site 1
## 2 http://example.com/path2 That website site 2
于 2016-01-17T14:11:18.023 回答