以下為實習被追殺的日子part1連結:
R實習筆記(一)-2008~2017年全臺一般空氣品質測站資料整理
爬爬網頁紓壓一百分,實習當中覺得很有趣的結果(◉ω◉)
主要練習CSS選擇器,拆解CSS龐大字串後,使用正則表達式抓取特定字串。
為了繪製AQI的日曆圖,需要收集到AQI的色碼,所以我就潛入html中啦~
圖一 AQI日曆圖
圖二 實際html網頁中AQI色碼存在位置示意圖
windows version 1803 (10.0.17134) , R version 3.5.1 , RStudio version 1.1.453
xml2 , rvest , magrittr
代表AQI前方接,而AQI和back中間接,只要符合這樣模式的字串,就會被抓取。
因為要避開冒號有兩個位置,而只抓取color:會抓到前方的RGB色碼,所以直接 抓取background-color:中b的位置後,再加上background-color:的字元數後, 即可取得第二個冒號的位置。
library(xml2);library(rvest);library("magrittr")
AQIcolor<-function(url){
#1.抓html檔
css<-url%>% read_html() %>% html_nodes("head>link") %>% html_attr("href") #爬網頁
css.text<-paste0("https://taqm.epa.gov.tw",css)%>% read_html() %>% html_nodes("body") %>% html_text
#2.拆字串
text <-strsplit(css.text,"}")
text<-text[[1]][which(grepl(".AQI.+back",text[[1]])==T)]
aim<-regexpr(text,pattern="background-color:")+nchar("background-color:")
outcome<-substring(text,aim)
}
1.放入環保署英文版網址。
2.放入環保署中文版網址。
3.建立AQI色表:
- Range:AQI數值區間
- English_RGB:英文版網頁RGB色碼
- TW_RGB:中文版網頁RGB色碼
#目標:環保署英文版網址
en.rgb<-AQIcolor("https://taqm.epa.gov.tw/taqm/en/b0201.aspx")
#目標:環保署中文版網址
tw.rgb<-AQIcolor("https://taqm.epa.gov.tw/taqm/tw/b0201.aspx")
AQI<-list("Range" = c("0~50","51~100", "101~150", "151~200", "201~300" ,"301~500"),"English_RGB"=en.rgb,"TW_RGB"=tw.rgb) %>% as.data.frame()
knitr::kable(AQI,format = "markdown",align = 'c')
| Range | English_RGB | TW_RGB |
|---|---|---|
| 0~50 | #0f0 | #00e800 |
| 51~100 | #ff0 | #ff0 |
| 101~150 | #ff7e00 | #ff7e00 |
| 151~200 | red | red |
| 201~300 | purple | #8f3f97 |
| 301~500 | #7e0023 | #7e0023 |
最後比較台灣環保署的中英文版網頁中,AQI區間:0-50和201-300的RGB色碼不同(●‘Д’●),剛看到爬完的結果時,我還以為我眼睛業障重。
圖三 台灣,美國和中國AQI色碼比較
我最後決定用英文版網頁的RGB色碼啦!
但是從網頁抓取的RGB色碼不能在R中直接使用,所以我還要寫個轉換RGB的code了。
knitr::kable(AQI[1:2],format = "markdown",align = 'c', padding = 2)
| Range | English_RGB |
|---|---|
| 0~50 | #0f0 |
| 51~100 | #ff0 |
| 101~150 | #ff7e00 |
| 151~200 | red |
| 201~300 | purple |
| 301~500 | #7e0023 |