安裝Selenium

原文附上供參考 利用R語言Rselenium控制瀏覽器,在操作前有2個檔案需先下載 :

Selenium Server standalone : 是1個 .jar檔,因為R目前還無法對Selenium直接進行測試,需要倚賴Java的幫助才能順利搭配套件驅動,這點Python倒是沒這煩惱XD

ChromeDriver : 是1個 .exe檔,不用納悶為什麼不附64位元的,因為就是只提供32位元的而已,小弟已經爬stackoverflow確認過了~有些人認為這也許和後面出現的1個bug有關係? Whatever, 裝就對了!

開始安裝吧~

首先,開啟命令提示字元,key入 : java -jar selenium-server-standalone-3.11.0.jar

再來,請將 chrome.exe 與 chromedriver.exe 都移動至 C: / Program Files (x86) / Google / Chrome / Application目錄下

最後,將此路徑 C: / Program Files (x86) / Google / Chrome / Application 添加到環境變量PATH的路徑中

啟動RSelenium

library(RSelenium)
## Warning: package 'RSelenium' was built under R version 3.4.4
rs.test <- remoteDriver(remoteServerAddr = "localhost", port = 4444, browserName = "chrome")
rs.test$open()
## [1] "Connecting to remote server"
## $applicationCacheEnabled
## [1] FALSE
## 
## $rotatable
## [1] FALSE
## 
## $mobileEmulationEnabled
## [1] FALSE
## 
## $networkConnectionEnabled
## [1] FALSE
## 
## $chrome
## $chrome$chromedriverVersion
## [1] "2.38.551601 (edb21f07fc70e9027c746edd3201443e011a61ed)"
## 
## $chrome$userDataDir
## [1] "C:\\Users\\TKU-ST~1\\AppData\\Local\\Temp\\scoped_dir11728_24027"
## 
## 
## $takesHeapSnapshot
## [1] TRUE
## 
## $pageLoadStrategy
## [1] "normal"
## 
## $databaseEnabled
## [1] FALSE
## 
## $handlesAlerts
## [1] TRUE
## 
## $hasTouchScreen
## [1] FALSE
## 
## $version
## [1] "65.0.3325.181"
## 
## $platform
## [1] "Windows NT"
## 
## $browserConnectionEnabled
## [1] FALSE
## 
## $nativeEvents
## [1] TRUE
## 
## $acceptSslCerts
## [1] FALSE
## 
## $acceptInsecureCerts
## [1] FALSE
## 
## $locationContextEnabled
## [1] TRUE
## 
## $webStorageEnabled
## [1] TRUE
## 
## $browserName
## [1] "chrome"
## 
## $takesScreenshot
## [1] TRUE
## 
## $javascriptEnabled
## [1] TRUE
## 
## $cssSelectorsEnabled
## [1] TRUE
## 
## $setWindowRect
## [1] TRUE
## 
## $unexpectedAlertBehaviour
## [1] ""
## 
## $webdriver.remote.sessionid
## [1] "ef52631844e0c23ac5657ef42edf0086"
## 
## $id
## [1] "ef52631844e0c23ac5657ef42edf0086"

成功驅動browser後( Chrome ),即可看到下面示圖

但如果你不幸出現了下圖這個bug,unable to create new service,以上的 Link 倒數第2位高手會告訴你該如何解決!!! Good Luck~

爬蟲變的好簡單

本次測試網站 : http://steve-chen.tw/,Go~

rs.test$navigate("http://steve-chen.tw/")
進入網站後,打開開發人員工具 透過色塊的提示,決定crawling的範圍 請注意 : 所標記的 div class = “Recent-Posts”…

這段Code

webElem <- rs.test$findElement(using = 'class', value = "Recent-Posts")
theText <- webElem$getElementText()
newText <- as.data.frame(t(theText))

最後一步驟,只要將爬下來的theText (list) 轉成 newText (data-frame)即完成階段性任務!謝謝大家。

以上感謝Steve Chen老師大方提供網站供學生實作