注意:这个例子是获取链接的一种非常基本的方法,因此需要进行调整以使其更加健壮。:)
我不知道这段代码有多么有用,但希望它可以让您了解前进的方向(只需将其复制并粘贴到 R 中,一旦您安装了包 RCurl 和 XML,它就是一个自包含的示例) :
library(RCurl)
library(XML)
get.links.on.page <- function(u) {
doc <- getURL(u)
html <- htmlTreeParse(doc, useInternalNodes = TRUE)
nodes <- getNodeSet(html, "//html//body//a[@href]")
urls <- sapply(nodes, function(x) x <- xmlAttrs(x)[[1]])
urls <- sort(urls)
return(urls)
}
# a naieve way of doing it. Python has 'urlparse' which is suppose to be rather good at this
get.root.domain <- function(u) {
root <- unlist(strsplit(u, "/"))[3]
return(root)
}
# a naieve method to filter out duplicated, invalid and self-referecing urls.
filter.links <- function(seed, urls) {
urls <- unique(urls)
urls <- urls[which(substr(urls, start = 1, stop = 1) == "h")]
urls <- urls[grep("http", urls, fixed = TRUE)]
seed.root <- get.root.domain(seed)
urls <- urls[-grep(seed.root, urls, fixed = TRUE)]
return(urls)
}
# pass each url to this function
main.fn <- function(seed) {
raw.urls <- get.links.on.page(seed)
filtered.urls <- filter.links(seed, raw.urls)
return(filtered.urls)
}
### example ###
seed <- "http://www.r-bloggers.com/blogs-list/"
urls <- main.fn(seed)
# crawl first 3 links and get urls for each, put in a list
x <- lapply(as.list(urls[1:3]), main.fn)
names(x) <- urls[1:3]
x
如果你把它复制并粘贴到R中,然后看x,我认为它会有意义。
不管怎样,祝朋友好运!托尼·布雷亚尔