评估Ruby上的javascript
我尝试获取网页的代码html,但网页包含一些生成我需要的数据的javascript代码。
http = Net::HTTP.new('localhost') path = '/files.php' # POST request -> logging in data = '' headers = { 'Referer' => 'http://localhost:8080/files.php', 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0', 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3', 'Content-Encoding' => 'gzip, deflate', 'Connection' => 'keep-alive', 'Cookie' => '' } resp, data = http.post(path, data, headers) puts resp.body
但这只返回html而不评估javascript。 我想在评估页面的javascript后获得最终的html。
做出的假设:您的Javascript位于网页上的单个标记中。 否则你将不得不通过寻找你想要的每一个j来解析。 你想要的gem被称为“therubyracer”,它将谷歌的v8 javascript执行引擎嵌入到你的ruby中。
转到您的命令行并安装therubyracer
gem install therubyracer
然后:
require 'v8' data = '' headers = { 'Referer' => 'http://localhost:8080/files.php', 'User-Agent' => 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0', 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3', 'Content-Encoding' => 'gzip, deflate', 'Connection' => 'keep-alive', 'Cookie' => '' } resp, data = http.post(path, data, headers) js = resp[resp.index('