【问题标题】:Scraping several webpages from a website (newspaper archive) using RSelenium使用 RSelenium 从网站(报纸档案)中抓取多个网页
【发布时间】:2022-01-12 03:43:22
【问题描述】:

根据here的解释,我设法从newspaper archive中抓取了一页。

现在我正在尝试通过运行一个代码来自动化访问页面列表的过程。 制作 URL 列表很容易,因为报纸的档案有类似的链接模式:

https://en.trend.az/archive/2021-XX-XX

问题在于编写一个循环来抓取标题、日期、时间、类别等数据。为简单起见,我尝试仅使用 2021-09-30 到 2021-10-02 的文章标题。

## Setting data frames

d1 <- as.Date("2021-09-30")
d2 <- as.Date("2021-10-02")

list_of_url <- character()   # or str_c()

## Generating subpage list 
 
for (i in format(seq(d1, d2, by="days"), format="%Y-%m-%d"))  {
  list_of_url[i] <- str_c ("https://en.trend.az", "/archive/", i)

# Launching browser

driver <- rsDriver(browser = c("firefox"))  #Version 93.0 (64-bit)
remDr <- driver[["client"]]
remDr$errorDetails
remDr$navigate(list_of_url[i])
   
   remDr0$findElement(using = "xpath", value = '/html/body/div[1]/div/div[1]/h1')$clickElement()
   
   webElem <- remDr$findElement("css", "body")
#scrolling to the end of webpage, to load all articles 
for (i in 1:25){
  Sys.sleep(2)
  webElem$sendKeysToElement(list(key = "end"))
} 

page <- read_html(remDr$getPageSource()[[1]])

# Scraping article headlines

get_headline <- page %>%
html_nodes('.category-article') %>% html_nodes('.article-title') %>% 
  html_text()
get_time <- str_sub(get_time, start= -5)

length(get_time)
   }
}

总长度应该是 157+166+140=463。事实上,我什至没有设法从一页收集所有数据(长度(get_time)= 126)

我认为在循环中的第一组命令之后,我在指定的3个日期获得了三个remDr,但它们后来没有被独立识别。

因此,我尝试在page &lt;- 之前或之后在第一个循环中启动第二个循环

  for (remDr0 in remDr) {
page <- read_html(remDr0$getPageSource()[[1]])
# substituted all remDr-s below with remDr0

page <- read_html(remDr$getPageSource()[[1]])
for (page0 in page)
# substituted all page-s below with page0

但是,这些尝试以不同的错误结束。

感谢专家的帮助,因为这是我第一次将 R 用于此类目的。

希望可以通过创建function 来纠正我创建的现有循环,或者甚至建议更短的路径。

【问题讨论】:

    标签: html r selenium web-scraping rvest


    【解决方案1】:

    为了抓取多个类别而略微扩大

        library(RSelenium)
        library(dplyr)
        library(rvest)
    

    提及日期期间

        d1 <- as.Date("2021-09-30")
        d2 <- as.Date("2021-10-02")
        dt = seq(d1, d2, by="days")#contains the date sequence
        
        #launch browser 
        driver <- rsDriver(browser = c("firefox"))  
        remDr <- driver[["client"]]
        
    ### `get_headline`  Function for newspaper headlines 
    
        get_headline = function(x){
          link = paste0( 'https://en.trend.az/archive/', x)
          remDr$navigate(link)
          remDr$findElement(using = "xpath", value = '/html/body/div[1]/div/div[1]/h1')$clickElement()
          webElem <- remDr$findElement("css", "body")
          #scrolling to the end of webpage, to load all articles 
          for (i in 1:25){
            Sys.sleep(1)
            webElem$sendKeysToElement(list(key = "end"))
          } 
          
          headlines = remDr$getPageSource()[[1]] %>% 
            read_html() %>%
            html_nodes('.category-article') %>% html_nodes('.article-title') %>% 
            html_text()
          headlines 
          return(headlines)
        }
    

    get_time发布时的函数

    get_time <- function(x){
      link = paste0( 'https://en.trend.az/archive/', x)
      remDr$navigate(link)
      remDr$findElement(using = "xpath", value = '/html/body/div[1]/div/div[1]/h1')$clickElement()
      webElem <- remDr$findElement("css", "body")
      #scrolling to the end of webpage, to load all articles 
      for (i in 1:25){
        Sys.sleep(1)
        webElem$sendKeysToElement(list(key = "end"))
      } 
      
      # Addressing selector of time on the website
      
      time <- remDr$getPageSource()[[1]] %>%
        read_html() %>%
        html_nodes('.category-article') %>% html_nodes('.article-date') %>% 
        html_text() %>%
        str_sub(start= -5)
      time
      return(time)
    }
    

    每天一页的所有文章的编号

    get_number <- function(x){
      link = paste0( 'https://en.trend.az/archive/', x)
      remDr$navigate(link)
      remDr$findElement(using = "xpath", value = '/html/body/div[1]/div/div[1]/h1')$clickElement()
      webElem <- remDr$findElement("css", "body")
      #scrolling to the end of webpage, to load all articles 
      for (i in 1:25){
        Sys.sleep(1)
        webElem$sendKeysToElement(list(key = "end"))
      } 
      
      # Addressing selectors of headlines on the website
      
      headline <- remDr$getPageSource()[[1]] %>% 
        read_html() %>%
        html_nodes('.category-article') %>% html_nodes('.article-title') %>% 
        html_text()
      number <- seq(1:length(headline))
      return(number)
    }
    

    收集所有函数到tibble

    get_data_table <- function(x){
    
          # Extract the Basic information from the HTML
          headline <- get_headline(x)
          time <- get_time(x)
          headline_number <- get_number(x)
    
          # Combine into a tibble
          combined_data <- tibble(Num = headline_number,
                                  Article = headline,
                                  Time = time) 
    }
    

    使用lapply 循环遍历dt 中的所有日期

        df = lapply(dt, get_data_table)
    

    【讨论】:

    • 非常感谢!它工作得很好!出于好奇,为什么最初的代码为每个日期打开一个新的 Firefox 窗口,而最近的代码在一个日期内完成了所有操作?
    • 是的。浏览器应该只打开一次并且应该在循环之外。
    猜你喜欢
    • 2020-08-05
    • 2013-07-08
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多