【发布时间】:2021-03-24 04:10:36
【问题描述】:
library(rvest)
library(RCurl)
library(XML)
library(stringr)
#Getting the number of Page
getPageNumber <- function(URL) {
print(URL)
parsedDocument <- read_html(URL)
pageNumber <- parsedDocument %>%
html_nodes(".al-pageNumber") %>%
html_text() %>%
as.integer()
return(ifelse(length(pageNumber) == 0, 0, max(pageNumber)))
}
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
firstPage <- getPageNumber(URL)
paste(firstPage)
if (firstPage == 5) {
nextPage <- 0
while (firstPage < nextPage | firstPage != nextPage) {
firstPage <- nextPage
URLwithPageNum <- paste(URL, firstPage-1, sep = "")
nextPage <- getPageNumber(URLwithPageNum)
}
}else {
print("The Year you provide is out of range, this journal only contain articles from 1994 to present")
}
}
}
findURL(2018)
上面的代码是我的 webscrape 的一部分。主要是我想做的是在给定参数年份的情况下获取所有期刊的页面。我相信我的 getPageNumber 是错误的,因为我只能获取从第一页看到的页面数量,而不是获取一年中给出的所有页面。
然后我的主要功能是根据页面错误地抓取网址。
我想补充一点,我一年最多想抓取的页面是 5
非常感谢任何帮助!提前谢谢你
【问题讨论】:
-
请给出一个您认为页码函数返回错误页数的示例 url,并指出正确的页数应该是多少
标签: html r if-statement url web-scraping