使用Mechanize获取JavaScript变量 [英] Get JavaScript variable using Mechanize

查看:120
本文介绍了使用Mechanize获取JavaScript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从



现在回答你的问题。当然,有可能提取令牌本身,但你必须以肮脏的方式进行。您必须等待,直到所有JS在页面上执行,然后获取文档正文并以某种方式提取它 - 一种方式可能是RegExp。



编辑:
Mechanize根据其他一些答案在这里不执行JS,这就是为什么你需要一个驱动器的宝石一个浏览器(watir就是一个很好的例子),但这会让我们回到上述问题。


I want to get a JavaScript variable from https://admin.booking.com/hotel/hoteladmin in head > script > var token.

I don't know how this variable is set by the browser because when I get this page from Mechanize I get:

var token = '' || 'empty-token',

Here is the code I use to GET this page:

login_url = "https://admin.booking.com/hotel/hoteladmin"
agent = Mechanize.new
agent.verify_mode= OpenSSL::SSL::VERIFY_NONE
page = agent.get(login_url)

解决方案

If you want to access this token via JavaScript in mechanize/watir, you need to be able to access it with your browsers developers tools as well.

Unfortunately the variable itself is enclosed in a scope, which makes it impossible to access it just like that. You can read more about the many different types of scopes in JS in this excellent post: What is the scope of variables in JavaScript?

Now to answer your question. Sure, it would be possible to extract the token itself, but you would have to do it in a dirty manner. You would have to wait untill all JS is executed on the page and then take the document body and extract it somehow - one way could be RegExp.

EDIT: Mechanize does according to a a few other answers here on SO not execute JS, which is why you need a gem that drives a browser (watir is a great example), but that drives us back to the problem described above.

这篇关于使用Mechanize获取JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆