问题描述
`library(rvest)
library(RCurl)
library(XML)
library(stringr)
#Getting the number of Page
getPageNumber <- function(URL){
parsedDocument = read_html(URL)
Sort1 <- html_nodes(parsedDocument,'div')
Sort2 <- Sort1[which(html_attr(Sort1,"class") == "pagination al-pagination")]
P <- str_count(html_text(Sort2),pattern = " \\d+\r\n")
return(ifelse(length(P) == 0,max(P)))
}
#Getting all articles based off of their DOI
getAllArticles <-function(URL){
parsedDocument = read_html(URL)
Sort1 <- html_nodes(parsedDocument,'div')
Sort2 <- Sort1[which(html_attr(Sort1,"class") == "al-citation-list")]
ArticleDOInumber = trimws(gsub(".*10.1093/dnares/","",html_text(Sort2)))
URL3 <- "https://doi.org/10.1093/dnares/"
URL4 <- paste(URL3,ArticleDOInumber,sep = "")
return(URL4)
}
Title <- function(parsedDocument){
Sort1 <- html_nodes(parsedDocument,'h4')
Title <- gsub("<a>\\n|\\n</a>",Sort1)
return(Title)
}
#main function with input as parameter year
findURL <- function(year_chosen){
if(year_chosen >= 1994){
noYearURL = glue::glue("https://academic.oup.com/dnaresearch/search-results?rg_IssuePublicationDate=01%2F01%2F{year_chosen}%20TO%2012%2F31%2F{year_chosen}")
pagesURl = "&fl_SiteID=5275&page="
URL = paste(noYearURL,pagesURl,sep = "")
#URL is working with parameter year_chosen
Page <- getPageNumber(URL)
if(Page == 5){
Page2 <- 0
while(Page < Page2 | Page != Page2){
Page <- Page2
URL3 <- paste(URL,Page-1,sep = "")
Page2 <- getPageNumber(URL3)
}
}
R_Data <- data.frame()
for(i in 0:ifelse((Page-1) > 0,(Page-1),0)){
URL2 <- getAllArticles(paste(URL,i,sep = ""))
for(j in 1:(length(URL2))){
parsedDocument <- read_html(URL2[j])
print(URL2[j])
R <- data.frame("Title" = Title(parsedDocument),stringsAsFactors = FALSE)
R_Data <- rbind(R_Data,R)
}
}
write.csv(R_Data,"Group4.csv",row.names = FALSE,sep = "\t")
} else {
print("The Year you provide is out of range,this journal only contain articles from 2005 to present")
}
}
findURL(2000)`
所以我试图在给定的年份抓取一个网站,在我的主函数中,我尝试遍历不同的页面。仅提取每篇文章的标题。
我不断收到此错误 -> open.connection(x,"rb") 中的错误:HTTP 错误 404
有些年份只有 3 页,所以我可以理解为什么可能会出现错误,但大多数文章都有 5 页的期刊。
预先感谢您的帮助!
解决方法
尚未完全检查,即未经过许多不同年份的测试,但由于 Page = 0 没有产生您可能想要的结果:
for(i in 1:Page)
代替
for(i in 0:ifelse((Page-1) > 0,(Page-1),0))
这可能会对 findURL
后面的逻辑产生影响。
此外,您的函数 Title
当前正在返回 html。不知道是不是故意的。
根据我建议的更改,您的代码现在会生成一个填充的 csv,其中包含大量重复信息,表明您可能想要重新访问 Title
函数。