2017-12-30 17 views
0

http://myneta.info/uttarpradesh2017/index.php?action=summary&subAction=candidates_analyzed&sort=candidate#summary에서 내 R 스튜디오로 테이블을 긁어 내려고합니다.myneta에서 테이블을 긁어 모으기 R

여기 코드

url<-'http://myneta.info/uttarpradesh2017/index.php?action=summary&subAction=candidates_analyzed&sort=candidate#summary' 
webpage<-read_html(url) 
candidate_info<- html_nodes(webpage,xpath='//*[@id="main"]/div/div[2]/div[2]/table') 
candidate_info<- html_table(candidate_info) 
head(candidate_info) 

그러나 어떤 출력을 얻는하지, 난 잘못하고있는 무슨 제안?

+0

무엇이 그 XPath로 안내 했습니까? – hrbrmstr

+0

크롬에서 페이지를 검사하고 HTML 태그의 xpath를 태그 위로 가져 가면 표가 강조 표시된 곳을 복사합니다. –

+1

답변에 다른 XPath를 제공했습니다. 복사 방법 (그리고 Selector Gadget 사용자를위한 큰 문제)은 _rendered_ HTML이 _source_ HTML과 상당히 다를 수 있으며'rvest' ('xml2', 정말로)는 _source_ HTML 만 처리한다는 것입니다. – hrbrmstr

답변

2

해당 사이트에는 매우 손상된 HTML이 있습니다. 그러나, 그것은 실행 가능합니다.

약간 덜 부서지기 쉬운 방법으로 노드를 대상으로 지정하는 것이 좋습니다. 아래의 XPath는 테이블의 내용으로 찾습니다.

html_table() 나는 수동으로 테이블을 만드는 일을 끝내기를 바랬다.

library(rvest) 

# helper to clean column names 
mcga <- function(x) { make.unique(gsub("(^_|_$)", "", gsub("_+", "_", gsub("[[:punct:][:space:]]+", "_", tolower(x)))), sep = "_") } 

pg <- read_html("http://myneta.info/uttarpradesh2017/index.php?action=summary&subAction=candidates_analyzed&sort=candidate#summary") 

# target the table 
tab <- html_node(pg, xpath=".//table[contains(thead, 'Liabilities')]") 

# get the rows so we can target columns 
rows <- html_nodes(tab, xpath=".//tr[td[not(@colspan)]]") 

# make a data frame 
do.call(
    cbind.data.frame, 
    c(lapply(1:8, function(i) { 
    html_text(html_nodes(rows, xpath=sprintf(".//td[%s]", i)), trim=TRUE) 
    }), list(stringsAsFactors=FALSE)) 
) -> xdf 

# make nicer names 
xdf <- setNames(xdf, mcga(html_text(html_nodes(tab, "th")))) # get the header to get column names 

str(xdf) 
## 'data.frame': 4823 obs. of 8 variables: 
## $ sno   : chr "1" "2" "3" "4" ... 
## $ candidate : chr "A Hasiv" "A Wahid" "Aan Shikhar Shrivastava" "Aaptab Urf Aftab" ... 
## $ constituency : chr "ARYA NAGAR" "GAINSARI" "GOSHAINGANJ" "MUBARAKPUR" ... 
## $ party  : chr "BSP" "IND" "Satya Shikhar Party" "Islam Party Hind" ... 
## $ criminal_case: chr "0" "0" "0" "0" ... 
## $ education : chr "12th Pass" "10th Pass" "Graduate" "Illiterate" ... 
## $ total_assets : chr "Rs 3,94,24,827 ~ 3 Crore+" "Rs 75,106 ~ 75 Thou+" "Rs 41,000 ~ 41 Thou+" "Rs 20,000 ~ 20 Thou+" ... 
## $ liabilities : chr "Rs 58,46,335 ~ 58 Lacs+" "Rs 0 ~" "Rs 0 ~" "Rs 0 ~" ... 
관련 문제