Re: [问题] table问题(网页编码)

楼主: celestialgod (天)   2016-06-05 21:08:11
※ 引述《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

Links booklink

Contact Us: admin [ a t ] ucptt.com