为了在R中进行一些文本分析,我想下载几个设计非常相似的网页。我已经尝试了几页,这段代码确实只保留了我感兴趣的行。
thepage= readLines("http://example/xwfw_665399/s2510_665401/t1480900.shtml")
thepage2 = readLines("http://example/xwfw_665399/s2510_665401/2535_665405/t851768.shtml")
mypattern1 = '<P style=\"FONT.*\">'
datalines1 = grep(mypattern1,thepage[1:length(thepage)],value=TRUE)
datalines2 = grep(mypattern1,thepage2[1:length(thepage)],value=TRUE)
mypattern2 = '<STRONG>'
mypattern3 = '</STRONG>'
mypattern4 = '</P>'
page1=gsub(mypattern1,"",datalines1)
page1=gsub(mypattern2,"", page1)
page1=gsub(mypattern3,"",page1)
page1=gsub(mypattern4,"",page1)
page2=gsub(mypattern1,"",datalines2)
page2=gsub(mypattern2,"", page2)
page2=gsub(mypattern3,"",page2)
page2=gsub(mypattern4,"",page2)
如您所见,URL 非常相似,以 s2510_665401/结尾现在,我想知道,有没有办法在s2510_665401/后自动检索所有可能的文件并让我的代码运行它们?尽管在谷歌上搜索了一些内容,但我还是找不到任何东西。它需要编写一个函数吗?如果是这样,有人会指出我正确的方向吗?谢谢!
这不是一个最终的工作答案,我很少做网络抓取,所以不确定这对其他网页的推广程度如何,但它可能会帮助你朝着正确的方向前进。请考虑此页面。我们可以编写一个函数来提取所有.html
元素,然后我们可以使用相同的函数再次爬网以获取它们的引用。
因此,在下面的代码中,unique(refs_1)
包含所有.html
一级深的页面,unique(refs_2)
包含两级深的所有.html
页面。
您仍然需要一个包装器在一定次数的迭代后停止,也许可以防止重新抓取已经访问过的页面(setdiff(refs_2,refs_1)?
(等。
当你有所有的URL要抓取时(在本例中是unique(c(refs_1,refs_2))
,你应该将自己的读取脚本包装在一个函数中,并调用lapply(x,f)
,其中x是URL的列表/数组,f
是你的函数。
无论如何,希望这有帮助!
library(qdapRegex)
get_refs_on_page <- function(page){
refs = lapply( tryCatch({readLines(page)}, error=function(cond){return(NA)},warning=function(cond){return(NA)})
, function(x) {y=rm_between(x , "href="", """, extract=TRUE)[[1]]})
refs=unlist(refs)
refs = refs[!is.na(refs)]
return(refs)
}
thepage = 'https://stat.ethz.ch/R-manual/R-devel/library/utils/'
refs_1 = get_refs_on_page(thepage)
refs_2 = unlist(lapply(paste0(thepage,refs_1),get_refs_on_page))
示例输出:
> unique(c(refs_1,refs_2))
[1] "?C=N;O=D" "?C=M;O=A" "?C=S;O=A"
[4] "?C=D;O=A" "/R-manual/R-devel/library/" "DESCRIPTION"
[7] "doc/" "html/" "?C=N;O=A"
[10] "?C=M;O=D" "?C=S;O=D" "?C=D;O=D"
[13] "/doc/html/R.css" "/doc/html/index.html" "../../../library/utils/doc/Sweave.pdf"
[16] "../../../library/utils/doc/Sweave.Rnw" "../../../library/utils/doc/Sweave.R" "Sweave.Rnw.~r55105~"