用R进行网络抓取谷歌新闻

276 阅读1分钟

本教程概述了如何用R编程语言提取谷歌新闻。当你需要在仪表板上显示你感兴趣的话题的通讯时,它是很有用的。在谷歌新闻中,你可以用你感兴趣的关键词搜索新闻。

在运行以下脚本之前,请确保安装rvest, dplyr and xml2 R软件包。该脚本返回以下几列(信息)。

  • 标题:文章的标题
  • 链接。文章的URL
  • 描述:文章的1或2行摘要
  • 来源:原始内容创建者的名字
  • 时间 : 文章发表的时间
news <- function(term) {
  
  require(dplyr)
  require(xml2)
  require(rvest)
  
  html_dat <- read_html(paste0("https://news.google.com/search?q=",term,"&hl=en-IN&gl=IN&ceid=US%3Aen"))
  
  dat <- data.frame(Link = html_dat %>%
                      html_nodes('.VDXfz') %>% 
                      html_attr('href')) %>% 
    mutate(Link = gsub("./articles/","https://news.google.com/articles/",Link))
  
  news_dat <- data.frame(
    Title = html_dat %>%
      html_nodes('.DY5T1d') %>% 
      html_text(),
    Link = dat$Link,
    Description =  html_dat %>%
      html_nodes('.Rai5ob') %>% 
      html_text()
  ) 
  
  # Extract Source and Time (To avoid missing content)
  prod <- html_nodes(html_dat, ".SVJrMe")
  Source <- lapply(prod, function(x) {
    norm <- tryCatch(html_node(x, "a") %>% html_text() ,
                     error=function(err) {NA})
  })
  
  time <- lapply(prod, function(x) {
    norm <- tryCatch(html_node(x, "time") %>% html_text(),
                     error=function(err) {NA})
  })
  
  mydf <- data.frame(Source = do.call(rbind, Source), Time = do.call(rbind, time), stringsAsFactors = F)
  dff <- cbind(news_dat, mydf) %>% distinct(Time, .keep_all = TRUE)
  
  return(dff)
}

newsdf <- news('indian"%20economy')

%20指的是两个词之间的空格。