本文整理汇总了Python中execjs.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: execute
def execute(bot, data, forward=True):
args = {"peer_id": data['peer_id'], "v": "5.60", }
if forward:
args.update({"forward_messages": data['message_id']})
code = bot.html_decode(' '.join(data['message'].split('<br>')[1:]))
JavaScript = execjs.get(execjs.runtime_names.Node)
print('JavaScript runtime -- ', execjs.get().name)
js = JavaScript.eval(code)
args['message'] = 'Выполнено {}\n{}'.format(execjs.get().name, js)
bot.Replyqueue.put(args)
示例2: unscramble_galaxy_script
def unscramble_galaxy_script(self):
# check script body
if not self.script_body.startswith('var Deuterium = '):
self.error_str = 'Invalid format of script body: cannot parse it!'
return None
# create JavaScript interpreter runtime
try:
js_runtime = execjs.get('Node')
except execjs_exceptions.RuntimeUnavailableError:
js_runtime = execjs.get() # default
# find galaxy script part
eval_start = self.script_body.find('eval(function(p,a,c,k,e,d)')
if eval_start == -1:
# try to find an end of galaxy rows declaration; maybe it is not packed (uni5)
eval_end = self.script_body.find("$('#galaxy').append(PrintRow());")
if eval_end == -1:
self.error_str = 'parse error (1) cannot find start (and end) of packed function'
return None
# if we are here, probably galaxy script is not scrambled
# eval_end is pointing at correct location, need to figure eval_start
rows_end_str = "$('#galaxy').append(PrintSelector(fleet_shortcut));"
eval_start = self.script_body.find(rows_end_str)
if eval_start == -1:
self.error_str = 'parse error (3) cannot find start of unpacked function'
return None
eval_start += len(rows_end_str)
eval_text = self.script_body[eval_start:eval_end]
eval_text = eval_text.strip()
eval_text = 'var row = []; ' + eval_text + '\nreturn row;'
#
ctx = js_runtime.compile(eval_text)
self.galaxy_rows = ctx.exec_(eval_text)
else:
# packed, as usual (uni4)
eval_end = self.script_body.find("$('#galaxy').append(PrintRow());")
if eval_end == -1:
self.error_str = 'parse error(2) cannot find end of function'
return None
eval_text = self.script_body[eval_start:eval_end]
eval_text = eval_text.strip()
# ^^ [eval(function(p,a,c,k,e,d){e=function(c){r... ...141|7866|u0426'.split('|')))]
eval_text = eval_text[5:-1]
# ^^ [function(p,a,c,k,e,d){e=functi... ...0426'.split('|'))]
eval_res = js_runtime.eval(eval_text)
# Now, eval_res is a string:
# row[12]={"planet":12,"id_planet":54448,"ally_planet":0,"metal":0,"crystal":0, ...
eval_res = 'var row = []; ' + eval_res + "\nreturn row;"
ctx = js_runtime.compile(eval_res)
self.galaxy_rows = ctx.exec_(eval_res)
return self.galaxy_rows
示例3: unscramble_galaxy_script
def unscramble_galaxy_script(self):
if not self.script_body.startswith('var Deuterium = '):
logger.error('Invalid format of script body: cannot parse it!')
return None
eval_start = self.script_body.find('eval(function(p,a,c,k,e,d)')
if eval_start == -1:
logger.error('parse error (1)')
return None
eval_end = self.script_body.find("$('#galaxy').append(PrintRow());")
if eval_end == -1:
logger.error('parse error (2)')
return None
eval_text = self.script_body[eval_start:eval_end]
eval_text = eval_text.strip()
logger.debug('eval [{0}]'.format(eval_text))
# ^^ [eval(function(p,a,c,k,e,d){e=function(c){r... ...141|7866|u0426'.split('|')))]
inner_eval = eval_text[5:-1]
logger.debug('inner eval [{0}]'.format(inner_eval))
# ^^ [function(p,a,c,k,e,d){e=functi... ...0426'.split('|'))]
#
# create JS interptreter and eval that
js_runtimes = execjs.available_runtimes()
if 'Node' in js_runtimes:
js = execjs.get('Node')
else:
js = execjs.get() # default
logger.debug('Using [{0}] as JS runtime.'.format(js.name))
eval_res = js.eval(inner_eval)
# Now, eval_res is a string:
# row[12]={"planet":12,"id_planet":54448,"ally_planet":0,"metal":0,"crystal":0,
# "name":"\u0413\u043b\u0430\u0432\u043d\u0430\u044f \u043f\u043b\u0430\u043d\u0435\u0442\u0430",
# "planet_type":1,"destruyed":0,"image":"normaltempplanet02","last_active":60,"parent_planet":0,
# "luna_id":null,"luna_name":null,"luna_destruyed":null,"luna_diameter":null,"luna_temp":null,
# "user_id":71992,"username":"\u041e\u041b\u0415\u0413 \u041a\u0410\u0420\u041f\u0415\u041d\u041a\u041e",
# "race":4,"ally_id":0,"authlevel":0,"onlinetime":1,"urlaubs_modus_time":0,"banaday":0,"sex":1,
# "avatar":7,"user_image":"","ally_name":null,"ally_members":null,"ally_web":null,"ally_tag":null,
# "type":null,"total_rank":7865,"total_points":0};row[9]={"planet":9,"id_planet":54450,"ally_planet":0,
# "metal":0,"crystal":0,"name":"Arnon","planet_type":1,"destruyed":0,"image":"normaltempplanet08",
# "last_active":0,"parent_planet":0,"luna_id":null,"luna_name":null,"luna_destruyed":null,
# "luna_diameter":null,"luna_temp":null,"user_id":71995,"username":"minlexx","race":4,"ally_id":389,
# "authlevel":0,"onlinetime":0,"urlaubs_modus_time":0,"banaday":0,"sex":1,"avatar":5,
# "user_image":"71995_1440872455.jpg","ally_name":"Fury","ally_members":8,"ally_web":"",
# "ally_tag":"Fury","type":null,"total_rank":141,"total_points":115582};
# ...
# we ned to eval() this string again, slightly modified, to get resulting row:
eval_res = 'var row = []; ' + eval_res + "\nreturn row;"
ctx = js.compile(eval_res)
self.galaxy_rows = ctx.exec_(eval_res)
示例4: solve_cf_challenge
def solve_cf_challenge(self, resp, headers, **kwargs):
headers = headers.copy()
url = resp.url
parsed = urlparse(url)
domain = parsed.netloc
page = resp.content
kwargs.pop("params", None) # Don't pass on params
try:
# Extract the arithmetic operation
challenge = re.search(r'name="jschl_vc" value="(\w+)"', page).group(1)
builder = re.search(
r"setTimeout\(function\(\){\s+(var t,r,a,f.+?\r?\n[\s\S]+?a\.value =.+?)\r?\n", page
).group(1)
builder = re.sub(r"a\.value =(.+?) \+ .+?;", r"\1", builder)
builder = re.sub(r"\s{3,}[a-z](?: = |\.).+", "", builder)
except AttributeError:
# Something is wrong with the page. This may indicate Cloudflare has changed their
# anti-bot technique. If you see this and are running the latest version,
# please open a GitHub issue so I can update the code accordingly.
raise IOError(
"Unable to parse Cloudflare anti-bots page. Try upgrading cfscrape, or "
"submit a bug report if you are running the latest version."
)
# Lock must be added explicitly, because PyV8 bypasses the GIL
ctxt = execjs.get("PhantomJS")
# Safely evaluate the Javascript expression
answer = str(int(ctxt.eval(builder)) + len(domain))
params = {"jschl_vc": challenge, "jschl_answer": answer}
submit_url = "%s://%s/cdn-cgi/l/chk_jschl" % (parsed.scheme, domain)
headers["Referer"] = url
return requests.get(submit_url, params=params, headers=headers, **kwargs)
示例5: create_scraper
def create_scraper(cls, sess=None, js_engine=None):
"""
Convenience function for creating a ready-to-go requests.Session (subclass) object.
"""
if js_engine:
os.environ["EXECJS_RUNTIME"] = js_engine
js_engine = execjs.get().name
if not js_engine:
raise EnvironmentError("No Javascript runtime installed. "
"Please install Node.js or equivalent Javascript runtime. ")
#if not ("Node" in js_engine or "V8" in js_engine):
#raise EnvironmentError("Your Javascript runtime '%s' is not supported due to security concerns. "
#"Please use Node.js or PyV8. To force a specific engine, "
#"such as Node, call create_scraper(js_engine=\"Node\")" % js_engine)
scraper = cls(js_engine=js_engine)
if sess:
attrs = ["auth", "cert", "cookies", "headers", "hooks", "params", "proxies", "data"]
for attr in attrs:
val = getattr(sess, attr, None)
if val:
setattr(scraper, attr, val)
return scraper
示例6: main
def main():
parser = ArgumentParser()
parser.add_argument('--print-available-runtimes', action=PrintRuntimes)
parser.add_argument('-r', '--runtime', action='store', dest='runtime')
parser.add_argument('-e', '--eval', action='store', dest='expr')
parser.add_argument("--encoding", action="store", dest="files_encoding", default="utf8")
parser.add_argument(nargs="*", action='store', dest='files')
opts = parser.parse_args()
runtime = execjs.get(opts.runtime)
codes = []
for f in opts.files:
with io.open(f, encoding=opts.files_encoding) as fp:
codes.append(fp.read())
context = runtime.compile("\n".join(codes))
if opts.expr:
if isinstance(opts.expr, bytes):
expr = opts.expr.decode()
else:
expr = opts.expr
sys.stdout.write(repr(context.eval(expr)) + "\n")
else:
ret = context.eval(sys.stdin.read())
sys.stdout.write(repr(ret) + "\n")
示例7: _get_runntime
def _get_runntime():
"""
:param path: 加密js的路径,注意js中不要使用中文!估计是pyexecjs处理中文还有一些问题
:return: 编译后的js环境,不清楚pyexecjs这个库的用法的请在github上查看相关文档
"""
phantom = execjs.get() # 这里必须为phantomjs设置环境变量,否则可以写phantomjs的具体路径
with open(js_path, 'r') as f:
source = f.read()
return phantom.compile(source)
示例8: evaljs
async def evaljs(self, *, code:str):
"""eval JS code in Node.JS"""
code_clean = "{0}".format(code.strip("```"))
node = execjs.get("Node")
execute = node.eval(code_clean)
try:
result = node.eval(code_clean)
await self.bot.say(code.format(result))
except execjs.ProgramError as e:
await self.bot.say(code.format(type(e).__name__ + ': ' + str(e)))
示例9: __init__
def __init__(self, script, logger=None):
try:
import execjs
except ImportError:
raise ImportError('Please install PyExecJS')
self.runner = execjs.get()
self.logger = getLogger('js', logger)
self.ctx = self.runner.compile(self.HEADER + script)
示例10: book
def book(session, kid, action=None):
with open("./ios/bus.js") as r:
js = execjs.get("Node").compile(r.read())
if not action:
res = session.post('http://bus.kuas.edu.tw/API/Reserves/add', data="{busId:"+ kid +"}")
else:
kid['reserveId'] = int(kid['key'])
res = session.post('http://bus.kuas.edu.tw/API/Reserves/remove?_dc='+str(js.call('getTime')), data=json.dumps(kid))
resource = json.loads(res.content)
return resource['message']
示例11: list_js_runtimes
def list_js_runtimes():
ajsr = execjs.available_runtimes()
if len(ajsr) > 0:
print('Detected {0} JavaScript runtimes:'.format(len(ajsr)))
for js in ajsr:
jsr = execjs.get(js)
pref_str = ''
if js == 'Node':
pref_str = ' <== I prefer this one!'
print(' {0}: {1}{2}'.format(js, jsr.name, pref_str))
else:
print('No JS runtimes detected! Install Node.js, spidermonkey or something!')
sys.exit(0)
示例12: initialize_javascript_runtime
def initialize_javascript_runtime():
global jsrt, jsctx, jsinitcnt
pac_content = main_gfwlist2pac()
jsrts = execjs.available_runtimes()
logging.debug(str(jsrts.keys())) # [u'Node', u'SpiderMonkey', u'Spidermonkey']
# SpiderMonkey 引擎比Node引擎用内存与CPU资源少,速度更快。
# 在archlinux上是包会自动使用js185,js包和js17包都不认。
# 好像有很严重的内存泄漏
# 内存问题好像不是出在execjs上的,而是mitmproxy本身就有问题
# https://github.com/mitmproxy/mitmproxy/issues/620
# 如果这有真有内存问题的话,可以考虑试用pacparser包。
jsrt = execjs.get('SpiderMonkey')
# jsrt = execjs.get('Node')
jsctx = jsrt.compile(pac_content)
jsinitcnt += 1
return
示例13: run_script
def run_script(code, func_name, func_input, errorlogger) :
sandboxcode = """
"use strict";
var vm = require('vm');
function safe_run(code, func_name, input) {
var vm_output = [];
var sandbox = { vm_input : input,
vm_output: vm_output,
require : function() {throw Error('require not allowed');}}
vm.createContext(sandbox);
vm.runInContext('"use strict";\\n'+code,sandbox,{'timeout':200});
vm.runInContext('vm_output.push('+func_name+'(vm_input))',sandbox,{'timeout':200});
return vm_output[0];
}
"""
js_ctx = execjs.get('Node').compile(sandboxcode)
try:
response = js_ctx.call('safe_run',code,func_name,func_input)
# except execjs.ProgramError as e:
# print str(e)
# return {'error':str(e)}
# except execjs.RuntimeError as e:
# print str(e)
# return {'error':str(e)}
except execjs.Error as e:
print str(e)
errorlogger.log_error(str(e))
return {}
except:
print traceback.format_exc()
errorlogger.log_error('Error: Unknown Error')
return {}
print response
return response
示例14: __init__
def __init__(self, script, logger=None, domain=""):
try:
import execjs
except ImportError:
raise ImportError('Please install PyExecJS')
self.runner = execjs.get()
self.logger = getLogger('js', logger)
window_emulator = self.HEADER
if domain:
window_emulator += "document.domain = '" + domain + "';"
window_emulator += """
if (typeof(location) === "undefined") {
var location = window.location = {
host: document.domain
};
}
"""
self.ctx = self.runner.compile(window_emulator + script)
示例15: list_js_runtimes
def list_js_runtimes():
# AttributeError: module 'execjs' has no attribute 'available_runtimes'
try:
ajsr = execjs.available_runtimes()
except AttributeError:
# Newer execjs does not have available_runtimes() method?
ajsr = []
supported_runtimes = execjs.runtimes()
for sr in supported_runtimes:
if supported_runtimes[sr].is_available():
ajsr.append(sr)
if len(ajsr) > 0:
print('Detected {0} JavaScript runtimes:'.format(len(ajsr)))
for js in ajsr:
jsr = execjs.get(js)
pref_str = ''
if js == 'Node':
pref_str = ' <== I prefer this one!'
print(' {0}: {1}{2}'.format(js, jsr.name, pref_str))
else:
print('No JS runtimes detected! Install Node.js, spidermonkey or something!')
sys.exit(0)