Ruby Nokogiri Javascript解析

noh*_*eye 5 javascript ruby nokogiri

我需要从网站解析数组。我要解析的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";
Run Code Online (Sandbox Code Playgroud)

我通过类似的东西得到整个JavaScript:

product_page = Nokogiri::HTML(open(full_url))    
product_page.css("div#main_column script")[0]
Run Code Online (Sandbox Code Playgroud)

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

Ron*_*lic 2

如果我没看错的话,您正在尝试解析 JavaScript 并获取包含图像 URL 的 Ruby 数组,是吗?

Nokogiri 只解析 HTML/XML,所以你需要一个不同的库;粗略搜索会发现RKelly库,它有一个parse函数,可以接受 JavaScript 字符串并返回解析树。

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

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

/^\s*_arPic\[\d\] = "(.+)";$/
Run Code Online (Sandbox Code Playgroud)

可能是一个很好的入门正则表达式。