如何使用 rvest 将 Google 新闻结果抓取到 data.frame

How to scrape Google News results into a data.frame with rvest

通过其他 SO 问题,我找到了如何获得头条新闻,但我不知道 Google 代码将链接存储在哪里。

我想要 2 列 data.frame 标题及其相应链接。

library(rvest)
library(tidyverse)


dat <- read_html("https://news.google.com/search?q=coronavirus&hl=en-US&gl=US&ceid=US%3Aen") %>%
  html_nodes('.DY5T1d') %>% #
  html_text()

dat

经过大量检查 Google 网络代码后,我找到了我要找的东西。我也看到了描述,所以我基本上重新构建了 Google 新闻 RSS 提要。

library(rvest)
library(tidyverse)


news <- function(term) {
  
  html_dat <- read_html(paste0("https://news.google.com/search?q=",term,"&hl=en-US&gl=US&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
  )
  
  return(news_dat)
}

news("coronavirus")