2017-08-12 68 views
0

使用HTML會話鏈接我試圖瀏覽到一個網站上的鏈接。除了一個鏈接,所有鏈接都可以工作。結果如下。導航到R中

> mcsession<-html_session("http://www.moneycontrol.com/financials/tataconsultancyservices/balance-sheetVI/TCS#TCS") 

> mcsession<-mcsession %>% follow_link("Previous Years »") 
Error: No links have text 'Previous Years »' 
In addition: Warning message: 
In grepl(i, text, fixed = TRUE) : input string 316 is invalid UTF-8 

> mcsession<-mcsession %>% follow_link("Balance Sheet") 
Navigating to /financials/tataconsultancyservices/balance-sheetVI/TCS#TCS 
Warning message: 
In grepl(i, text, fixed = TRUE) : input string 316 is invalid UTF-8 

任何想法爲什麼發生這種情況?

+0

如果你看看頁面,你會發現你並不是針對普通鏈接。事實上,點擊一下前幾年的不加載一個新的頁面,而是返回名爲'post_prevnext()'的JavaScript函數。據我所知,'rvest'不能跟隨那個鏈接,因爲它不是真的到另一個頁面的鏈接。我認爲你最好的選擇是使用'RSelenium'來編程瀏覽頁面,以便做你想做的事。 –

回答

2

這是不正常的鏈接 - 這是JavaScript的。我不知道有rvest做的一種方式,但你可以使用RSelenium,基本上可以自動地執行正常的瀏覽器窗口。它比直接抓取要慢,但是您可以自動執行任何可以手動執行的操作。這適用於我(在Windows 10上使用chrome)...

library(RSelenium) 
rD <- rsDriver(port=4444L,browser="chrome") 
remDr <- rD$client 

remDr$navigate("http://www.moneycontrol.com/financials/tataconsultancyservices/balance-sheetVI/TCS#TCS") 

firstpage <- remDr$getPageSource() #you can use this to get the first table 

#(1) 
webElem1 <- remDr$findElement(using = 'partial link text', value = "Previous Years") 
webElem1$clickElement() 

nextpage <- remDr$getPageSource() #you can use this to get the next page for previous years 

#repeat from #(1) to go back another page etc 

remDr$closeall() #when you have finished.