Ruby Nokogiri Javascript解析

我需要从一个网站解析一个数组。 我要解析的Javascript部分如下所示:

_arPic[0] = "http://example.org/image1.jpg"; _arPic[1] = "http://example.org/image2.jpg"; _arPic[2] = "http://example.org/image3.jpg"; _arPic[3] = "http://example.org/image4.jpg"; _arPic[4] = "http://example.org/image5.jpg"; _arPic[5] = "http://example.org/image6.jpg"; 

我通过类似的东西获得整个javascript:

 product_page = Nokogiri::HTML(open(full_url)) product_page.css("div#main_column script")[0] 

有没有一种简单的方法来解析所有变量?

如果我正确地读了你,你试图解析JavaScript并获得一个带有图像URL的Ruby数组吗?

Nokogiri只解析HTML / XML,因此您需要一个不同的库; 粗略搜索会打开RKelly库,它具有一个parse函数,该函数接受一个JavaScript字符串并返回一个解析树。

一旦你有一个解析树,你将需要遍历它并通过名称找到感兴趣的节点(例如_arPic ),然后在赋值的另一侧获取字符串内容。

或者,如果它不必太强大(并且它不会),你可以使用正则表达式来搜索JavaScript,如果可能的话:

 /^\s*_arPic\[\d\] = "(.+)";$/ 

可能是一个很好的首发正则表达式。

简单的方法:

 _arPic = URI.extract product_page.css("div#main_column script")[0].text 

可以缩短为:

 _arPic = URI.extract product_page.at("div#main_column script").text