我使用 R 来解析 html 代码,我想知道稀疏以下代码的最有效方法:
<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.
我想知道如何以非常有效的方式做到这一点:如何直接解析 javascript 中的数据列表? 谢谢。
最佳答案
我没有尝试你的代码,但我认为你的 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"
关于javascript - 如何用 R 解析 javascript 数据列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515062/