【问题标题】:How to parse javascript data list with R如何用 R 解析 javascript 数据列表
【发布时间】:2016-05-29 21:14:47
【问题描述】:

我使用 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 中的数据列表? 谢谢。

【问题讨论】:

  • 代码正在发挥作用。它没有错。或者你的意思是没有得到NULL 的键设备和显示类型?
  • 好吧,事实上,我很惊讶在输出中,environnement 被转换为“$nvironnemen”,我认为这是一个错误。你怎么解释这个?

标签: javascript r web-scraping


【解决方案1】:

我没有尝试您的代码,但我认为您的 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"

【讨论】:

  • 感谢@hrbrmstr 的帮助。我没有尝试评估功能,所以它是完美的!而事实上,你知道为什么使用 json,“environnement”变成“$nvironnemen”吗?
  • 您能否解释一下这个正则表达式“getD[[:alpha:]\(\)\\$\\.]+”是什么意思?它似乎删除了“()”之前和“()”中的所有字符。你如何“阅读”它?非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2014-11-22
  • 2015-10-22
  • 1970-01-01
  • 2023-03-26
  • 2012-02-15
相关资源
最近更新 更多