Re: [問題] table問題(網頁編碼)

看板R_Language作者 (天)時間9年前 (2016/06/05 21:08), 9年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/4 (看更多)
※ 引述《vicror84 (阿汘)》之銘言: : 請問我想把亞東健檢中心(http://depart.femh.org.tw/HMC/wholebody.html)的表格爬下 : 來,但會出現亂碼在windows系統中,使用R語言,抓取表格呈現出亂碼, : 我們將格式轉為繁體, : 還是會呈現亂碼,我們研究出所有BIG5編碼的網頁,轉換後,還是亂碼, : 程式如下: : library(XML) : URL = paste0("http://depart.femh.org.tw/HMC/wholebody.html") : doc<-htmlParse(URL,encoding="UTF-8") : tables<-readHTMLTable(doc,header=T,which = 2) : tables : dim(tables) : View(tables) 我不知道網頁的header跟內文的關係 我看charset是big5,不過我實際讀表格的資料,還是要用UTF8 所以我抓content的時候用big5是正常的,再用read_html with encoding utf8 之後再把utf8轉回去big5 (windows才要轉,mac, linux不用stri_conv那段) 之後就可以看到正常的表格內容了 library(httr) library(pipeR) library(xml2) library(stringi) library(stringr) tableContent <- GET("http://depart.femh.org.tw/HMC/wholebody.html") %>>% content("text", encoding = "BIG5") %>>% read_html("UTF-8") %>>% xml_find_all("//tr/td/table/tbody/tr") %>>% lapply(function(x){ output_text <- xml_find_all(x, "td") %>>% xml_text %>>% stri_conv(from = "UTF-8", to = "Big5") %>>% str_replace_all("\\s", "") if (length(output_text) >= 9 && length(output_text) <= 11) { return(c(rep("", 12-length(output_text)), output_text)) } else if (length(output_text) == 8) { return(c(output_text[1:4], unlist(rbind(output_text[5:8], rep("", 4))))) } else { return(output_text) } }) %>>% do.call(what = rbind) 結果截圖: http://i.imgur.com/eDG4uEY.png
函數說明可以往前翻我的文章,某一篇(#1N9lFXFI (R_Language))下面有一些說明 不懂再回文發問吧 #那串的用法:http://evolutionbrain.blogspot.tw/2015/08/ptt.html -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 211.76.63.212 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1465132100.A.58E.html ※ 編輯: celestialgod (211.76.63.212), 06/05/2016 21:15:10
文章代碼(AID): #1NL2H4ME (R_Language)
文章代碼(AID): #1NL2H4ME (R_Language)