如何使用R将a href更改为URL?

时间:2015-05-19 13:21:57

标签: r url href

如何使用R将href更改为有意义的URL?通过有意义的我理解一个地址,如果粘贴到浏览器将正确打开。

例如:

<a href="../../systemfit/html/systemfit.html">systemfit</a>

阅读: http://artax.karlin.mff.cuni.cz/r-help/library/systemfit/html/systemfit.control.html

成: http://artax.karlin.mff.cuni.cz/r-help/library/systemfit/html/systemfit.html

我的工作是:

collectLinks <- function(x){
library(stringi)
fileUrl <- (x)
html <- paste(readLines(fileUrl, warn=FALSE), collapse="\n")
matched <- stri_match_all_regex(html, "<a href=\"(.*?)\"")
matched[[1]][, 2]
}

links <- collectLinks("http://artax.karlin.mff.cuni.cz/r-help/library/systemfit/html/systemfit.control.html")

函数collectLinks采用包含URL作为输入的字符串。它返回一个href内容的字符向量,可以在x上找到。

接下来我要做的是浏览链接中的每个元素并从中提取href内容。但是:

[1] "../../systemfit/html/systemfit.html"      "../../systemfit/html/solve.html"      
[3] "../../systemfit/html/det.html"         "../../systemfit/html/systemfit.html"  
[5] "mailto:arne.henningsen@googlemail.com" "../../systemfit/html/systemfit.html"  
[7] "00Index.html"  

不是有意义的网址。

readLines(links[1])
Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
cannot open file '../../systemfit/html/systemfit.html': No such file or    directory

我想知道是否有一种通用方法可以将href内容转换为有意义的URL,这可以进一步利用?

1 个答案:

答案 0 :(得分:1)

library(XML)
k1<-getHTMLLink("http://artax.karlin.mff.cuni.cz/r-help/library/systemfit/html/systemfit.control.html")
#k1[6] is what you are looking for:
>k1[6]
[1] "../../systemfit/html/systemfit.html"
k2<-htmlParse(sub("../..", "http://artax.karlin.mff.cuni.cz/r-help/library",k1[6]))