2017-08-12 31 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.