getPostOffice <- function(){
#營業場所一覽
url_office="http://www.post.gov.tw/post/internet/I_location/index_all.html"
res=GET(url_office,encoding="UTF-8")
con=content(res,"text",encoding="UTF-8")
#留意此要有encoding,否則會出現unicode編碼
con_par=htmlParse(con,encoding="UTF8")
#抓出所有郵局的資料
office_list=getNodeSet(con_par,"//tr")
#總計有幾家郵局
ttl_office_cnt=length(office_list)
#抓取明細資料開始
post=c()
atm=c()
post_code=c()
computer_code=c()
store_nm=c()
computer_name=c()
store_link=c()
addr=c()
post_tel=c()
remit_tel=c()
#從2開始,因為第一筆為title
for(office_no in 2:ttl_office_cnt){
#首先第一為確認郵局有郵務或ATM
xml_str=xmlChildren(office_list[[office_no]])
img=xmlToList(xml_str[1]$td)
#先設定郵局服務為NA,再依其提供的部分更新為Y
#office_no需要減一,因為這樣資料表格才會從第一筆開始
post[office_no-1]="NA"
atm[office_no-1]="NA"
for(img_cnt in 1:(length(img)-1)){
if(img[img_cnt]$img["alt"]=="郵局"){post[office_no-1]="Y"}
if(img[img_cnt]$img["alt"]=="ATM"){atm[office_no-1]="Y"}
}
#第二為確認郵局郵遞區號/電腦局號等
post_code[office_no-1]=xmlToList(xml_str[3]$td)$text
computer_code[office_no-1]=xmlToList(xml_str[5]$td)$text
store_nm[office_no-1]=xmlToList(xml_str[7]$td)$a$text
store_link[office_no-1]=xmlToList(xml_str[7]$td)$a$.attrs["href"]
computer_name[office_no-1]=xmlToList(xml_str[9]$td)$text
addr[office_no-1]=xmlToList(xml_str[11]$td)$text
if(is.null(xmlToList(xml_str[13]$td))==FALSE){
post_tel[office_no-1]=xmlToList(xml_str[13]$td)
}else{post_tel[office_no-1]="NA"}
if(is.null(xmlToList(xml_str[15]$td))==FALSE){
remit_tel[office_no-1]=xmlToList(xml_str[15]$td)
}else{remit_tel[office_no-1]="NA"}
}
office_data=data.frame(brand_nm="郵局", kind="全國營業據點",
store_nm, store_link, computer_name,
post, atm, post_code, computer_code,
addr, post_tel, remit_tel, stringsAsFactors=FALSE)
return(office_data)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.