행 수가 다른 Rvest 스크랩 Google 뉴스

Nov 27 2020

Rvest를 사용하여 Google 뉴스를 스크랩하고 있습니다.
그러나 다른 키워드에서 때때로 "시간"요소에 누락 된 값이 있습니다. 값이 누락 되었기 때문에 스크랩 결과의 데이터 프레임에 대해 "다른 행 수 오류"가 발생합니다.
이러한 결 측값에 대해 NA를 채울 수 있습니까?

아래는 내가 사용하는 코드의 예입니다.

html_dat <- read_html(paste0("https://news.google.com/search?q=",Search,"&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,
   Description =  html_dat %>%
   html_nodes('.Rai5ob') %>% 
   html_text(),
   Time =  html_dat %>%
   html_nodes('.WW6dff') %>%
   html_text() 
 )    

답변

1 Dave2e Nov 27 2020 at 21:24

보고 계신 정확한 페이지를 모른 채 첫 번째 Google 뉴스 페이지를 사용해 보았습니다.

Rvest 페이지에서 html_node(s없이) NA 인 경우에도 항상 값을 반환합니다. 따라서 벡터의 길이를 동일하게 유지하려면 원하는 모든 데이터 노드에 대한 공통 부모 노드를 찾아야했습니다. 그런 다음 각 노드에서 원하는 정보를 구문 분석합니다.

Title 노드가 가장 완전하다고 가정하고 한 단계 위로 올라가 xml_parent()동일한 수의 설명 노드를 검색하려고 시도했지만 작동하지 않았습니다. 그런 다음을 사용하여 2 단계를 시도했는데 xml_parent() %>% xml_parent()작동하는 것 같습니다.

library(rvest)

url <-"https://news.google.com/topstories?hl=en-US&gl=US&ceid=US:en"
html_dat <- read_html(url)

Title = html_dat %>%  html_nodes('.DY5T1d') %>%   html_text()

# Link = dat$Link
Link = html_dat %>%  html_nodes('.VDXfz') %>%   html_attr('href') 
Link <-  gsub("./articles/", "https://news.google.com/articles/",Link)

#Find the common parent node 
#(this was trial and error) Tried the parent then the grandparent
Titlenodes <- html_dat %>%  html_nodes('.DY5T1d') %>% xml_parent()  %>% xml_parent() 
Description =  Titlenodes %>%  html_node('.Rai5ob') %>%  html_text()
Time =  Titlenodes %>%  html_node('.WW6dff') %>%   html_text() 
 
answer <- data.frame(Title, Time, Description, Link)