2016-05-29 19 views
4

JavaScript的数据表我用R解析HTML代码,我想知道最有效的方式,以疏下面的代码:如何分析有R

<script type="text/javascript"> 
var utag_data = { 
    environnement : "prod", 
    device : getDevice(), 
    displaytype : getDisplay($(window).innerWidth()), 
    pagename : "adview", 
    pagetype : "annonce"}</script> 

我开始这样做:

infos = unlist(xpathApply(page, 
          '//script[@type="text/javascript"]', 
          xmlValue)) 
infos=gsub('\n| ','',infos) 
infos=gsub("var utag_data = ","",infos) 
fromJSON(infos) 

而且上面的代码返回财产以后很奇怪:

$nvironnemen 
[1] "prod" 

$evic 
NULL 

$isplaytyp 
NULL 

$agenam 
[1] "adview" etc. 

我想知道如何做到这一点非常efficien t方式:如何直接解析javascript中的数据列表? 谢谢。

+0

代码正在完成其工作。它没有错。或者你的意思是没有获得'NULL'键设备和displaytyp? – agustin

+0

好的,事实上,我很惊讶在输出中,环境变成了“$ nvironnemen”,我认为这是一个错误。你怎么能解释这一点? –

回答

3

我没有尝试过你的代码,但我认为你的gsub()正则表达式可能是过分的(这可能导致名称消失)。

它可以运行使用V8包javascript代码,但它 将无法​​执行基于DOM的getDevice()getDisplay() 功能,因为它们没有在V8引擎中存在:

library(V8) 
library(rvest) 

pg <- read_html('<script type="text/javascript"> 
var utag_data = { 
    environnement : "prod", 
    device : getDevice(), 
    displaytype : getDisplay($(window).innerWidth()), 
    pagename : "adview", 
    pagetype : "annonce"}</script>') 


script <- html_text(html_nodes(pg, xpath='//script[@type="text/javascript"]')) 

ctx <- v8() 

ctx$eval(script) 
## Error: ReferenceError: getDevice is not defined 

但是,您可以补偿:

# we need to remove the function calls and replace them with blanks 
# since both begin with 'getD' this is pretty easy: 
script <- gsub("getD[[:alpha:]\\(\\)\\$\\.]+,", "'',", script) 

ctx$eval(script) 
ctx$get("utag_data") 

## $environnement 
## [1] "prod" 
## 
## $device 
## [1] "" 
## 
## $displaytype 
## [1] "" 
## 
## $pagename 
## [1] "adview" 
## 
## $pagetype 
## [1] "annonce" 
+0

谢谢@hrbrmstr的帮助。我没有尝试评估功能,所以它是完美的!事实上,你知道为什么用json,“环境”变成“$ nvironnemen”吗? –

+0

你能否也请解释一下这个正则表达式“getD [[:alpha:] \\(\\)\\ $ \\。] +”是什么意思?它似乎删除“()”之前和“()”中的所有字符。你如何“读”它?非常感谢你。 –