javascript - 如何用 R 解析 javascript 数据列表

标签 javascript r web-scraping

我使用 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/

相关文章:

python - 从 html span 中检索内容字段

javascript - 背景图片在 Firefox 和 IE 中不显示

javascript - 无法读取未定义的属性 'encrypt'

r - 列表中向量的名称

r - 将数据曲线拟合到R?

function - R:外循环功能不起作用

python - Scrapy 结合文本和粗体

Python Scrapy 抓取垃圾值

javascript - 离线保存包含 javascript 的网页

javascript - 嵌套 div 在下拉值选择上显示和隐藏