수색…


비고

스크래핑 은 컴퓨터를 사용하여 웹 페이지의 코드를 검색하는 것을 말합니다. 코드를 얻은 후에는 R에서 추가로 사용할 수 있도록 유용한 형식으로 파싱 해야합니다.

베이스 R에는 이러한 프로세스에 필요한 많은 도구가 없기 때문에 스크래핑 및 구문 분석은 일반적으로 패키지로 수행됩니다. 일부 패키지는 스크래핑 ( RSelenium , httr , curl , RCurl ), 구문 분석 ( XML , xml2 ) 및 일부 ( rvest )에 가장 유용합니다.

관련 프로세스는 웹 페이지와 달리 기계가 읽을 수있는 데이터를 반환하는 웹 API를 고칩니다. 동일한 패키지 중 많은 수가 둘 다 사용됩니다.

적법

서버로드 증가 또는 데이터 소유에 대한 우려로 인해 일부 웹 사이트는 긁히는 것에 반대합니다. 웹 사이트에서 스크랩하는 것을 금지하는 경우 이용 약관에 따라 스크랩하는 것은 불법입니다.

rvest로 기본 스크래핑하기

rvest 는 Hadley Wickham이 Python의 Beautiful Soup 에서 영감을 얻은 웹 스크래핑 및 구문 분석을위한 패키지입니다. Hadley의 xml2 패키지의 HTML 구문 분석을위한 libxml2 바인딩을 활용합니다.

tidyverse의 한 부분으로, rvest배관된다 . 그것은 사용

  • xml2::read_html 을 사용하여 웹 페이지의 HTML을 다 xml2::read_html ,
  • 그런 다음 CSS 또는 XPath 선택기를 사용하여 html_nodehtml_nodes 함수로 하위 집합을 만들 수 있습니다.
  • html_texthtml_table 과 같은 함수를 사용하여 R 객체로 구문 분석됩니다.

R의 Wikipedia 페이지에서 이정표를 긁어 내면 코드는 다음과 같이 보입니다.

library(rvest)

url <- 'https://en.wikipedia.org/wiki/R_(programming_language)'

        # scrape HTML from website
url %>% read_html() %>% 
    # select HTML tag with class="wikitable"
    html_node(css = '.wikitable') %>% 
    # parse table into data.frame
    html_table() %>%
    # trim for printing
    dplyr::mutate(Description = substr(Description, 1, 70))

##    Release       Date                                                  Description
## 1     0.16            This is the last alpha version developed primarily by Ihaka 
## 2     0.49 1997-04-23 This is the oldest source release which is currently availab
## 3     0.60 1997-12-05 R becomes an official part of the GNU Project. The code is h
## 4   0.65.1 1999-10-07 First versions of update.packages and install.packages funct
## 5      1.0 2000-02-29 Considered by its developers stable enough for production us
## 6      1.4 2001-12-19 S4 methods are introduced and the first version for Mac OS X
## 7      2.0 2004-10-04 Introduced lazy loading, which enables fast loading of data 
## 8      2.1 2005-04-18 Support for UTF-8 encoding, and the beginnings of internatio
## 9     2.11 2010-04-22                          Support for Windows 64 bit systems.
## 10    2.13 2011-04-14 Adding a new compiler function that allows speeding up funct
## 11    2.14 2011-10-31 Added mandatory namespaces for packages. Added a new paralle
## 12    2.15 2012-03-30 New load balancing functions. Improved serialization speed f
## 13     3.0 2013-04-03 Support for numeric index values 231 and larger on 64 bit sy

이렇게하면 data.frame이 반환되지만 스크랩 된 데이터의 경우와 마찬가지로 더 많은 데이터 정리가 필요합니다. 여기에는 날짜 형식 지정, NA 삽입 등이 포함됩니다.

일관성이 떨어지는 직사각형 형식의 데이터는 반복적으로 또는 더 많은 구문 분석을 성공적으로 수행 할 수 있습니다. 웹 사이트 콘텐츠를 삽입 할 jQuery를 또는 다른 수단을 사용한다면, read_html 긁어 불충분 할 수 있으며, 같은 더 강력한 스크레이퍼 RSelenium 필요할 수 있습니다.

로그인이 필요할 때 rvest 사용

나는 웹을 스크래핑 할 때 웹 사이트에 로그인하기 위해 사용자 아이디와 패스워드를 입력하는 방법과 관련된 일반적인 문제에 직면했다.

내 대답을 추적하기 위해 만든이 예제에서는 오버플로 스택에 게시했습니다. 전반적인 흐름은 로그인하고 웹 페이지로 이동하여 정보를 수집하고 데이터 프레임을 추가 한 다음 다음 페이지로 이동하는 것입니다.

library(rvest) 

#Address of the login webpage
login<-"https://stackoverflow.com/users/login?ssrc=head&returnurl=http%3a%2f%2fstackoverflow.com%2f"

#create a web session with the desired login address
pgsession<-html_session(login)
pgform<-html_form(pgsession)[[2]]  #in this case the submit is the 2nd form
filled_form<-set_values(pgform, email="*****", password="*****")
submit_form(pgsession, filled_form)

#pre allocate the final results dataframe.
results<-data.frame()  

#loop through all of the pages with the desired info
for (i in 1:5)
{
  #base address of the pages to extract information from
  url<-"http://stackoverflow.com/users/**********?tab=answers&sort=activity&page="
  url<-paste0(url, i)
  page<-jump_to(pgsession, url)

  #collect info on the question votes and question title
  summary<-html_nodes(page, "div .answer-summary")
  question<-matrix(html_text(html_nodes(summary, "div"), trim=TRUE), ncol=2, byrow = TRUE)

  #find date answered, hyperlink and whether it was accepted
  dateans<-html_node(summary, "span") %>% html_attr("title")
  hyperlink<-html_node(summary, "div a") %>% html_attr("href")
  accepted<-html_node(summary, "div") %>% html_attr("class")

  #create temp results then bind to final results 
  rtemp<-cbind(question, dateans, accepted, hyperlink)
  results<-rbind(results, rtemp)
}

#Dataframe Clean-up
names(results)<-c("Votes", "Answer", "Date", "Accepted", "HyperLink")
results$Votes<-as.integer(as.character(results$Votes))
results$Accepted<-ifelse(results$Accepted=="answer-votes default", 0, 1)

이 경우 루프는 5 페이지로 제한되며 응용 프로그램에 맞게 변경해야합니다. 나는 사용자 특정 값을 ******로 바꿨는데,이 것은 당신에게 문제에 대한 지침을 제공 할 것이다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow