• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python execjs.get函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中execjs.get函数的典型用法代码示例。如果您正苦于以下问题:Python get函数的具体用法?Python get怎么用?Python get使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了get函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:REDxEYE,项目名称:VK_BOT,代码行数:11,代码来源:CommandModule.py


示例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
开发者ID:minlexx,项目名称:xnova_galaxy_parser,代码行数:53,代码来源:xnova_utils.py


示例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)
开发者ID:minlexx,项目名称:xnovacmd,代码行数:48,代码来源:xn_parser_galaxy.py


示例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)
开发者ID:ohaz,项目名称:TeamspeakIRC,代码行数:35,代码来源:cfscrape.py


示例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
开发者ID:jimf54,项目名称:KissNetwork.bundle,代码行数:28,代码来源:__init__.py


示例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")
开发者ID:Mondego,项目名称:pyreco,代码行数:27,代码来源:allPythonContent.py


示例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)
开发者ID:ResolveWang,项目名称:smart_login,代码行数:9,代码来源:login_direct.py


示例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)))
开发者ID:SinSiXX,项目名称:notsosuper_bot,代码行数:10,代码来源:Utils.py


示例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)
开发者ID:dasimon,项目名称:weboob,代码行数:10,代码来源:js.py


示例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']
开发者ID:registerAutumn,项目名称:flask_web,代码行数:12,代码来源:bus.py


示例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)
开发者ID:minlexx,项目名称:xnovacmd,代码行数:13,代码来源:galaxy_auto_parser.py


示例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
开发者ID:kitech,项目名称:triline,代码行数:17,代码来源:mitmis.py


示例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
开发者ID:enochcheung,项目名称:Social-Network-for-Robots,代码行数:41,代码来源:scripting.py


示例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)
开发者ID:laurentb,项目名称:weboob,代码行数:22,代码来源:js.py


示例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)
开发者ID:minlexx,项目名称:xnova_galaxy_parser,代码行数:22,代码来源:galaxy_auto_parser.py


示例16: solve_challenge

    def solve_challenge(self, body):
        try:
            js = re.search(r"setTimeout\(function\(\){\s+(var "
                        "s,t,o,p,b,r,e,a,k,i,n,g,f.+?\r?\n[\s\S]+?a\.value =.+?)\r?\n", body).group(1)
        except Exception:
            raise ValueError("Unable to identify Cloudflare IUAM Javascript on website. %s" % BUG_REPORT)

        js = re.sub(r"a\.value = (parseInt\(.+?\)).+", r"\1", js)
        js = re.sub(r"\s{3,}[a-z](?: = |\.).+", "", js)

        # Strip characters that could be used to exit the string context
        # These characters are not currently used in Cloudflare's arithmetic snippet
        js = re.sub(r"[\n\\']", "", js)

        if "parseInt" not in js:
            raise ValueError("Error parsing Cloudflare IUAM Javascript challenge. %s" % BUG_REPORT)

        # Use vm.runInNewContext to safely evaluate code
        # The sandboxed code cannot use the Node.js standard library
        js = "return require('vm').runInNewContext('%s', Object.create(null), {timeout: 5000});" % js

        try:
            node = execjs.get("Node")
        except Exception:
            raise EnvironmentError("Missing Node.js runtime. Node is required. Please read the cfscrape"
                " README's Dependencies section: https://github.com/Anorov/cloudflare-scrape#dependencies.")

        try:
            result = node.exec_(js)
        except Exception:
            logging.error("Error executing Cloudflare IUAM Javascript. %s" % BUG_REPORT)
            raise

        try:
            result = int(result)
        except Exception:
            raise ValueError("Cloudflare IUAM challenge returned unexpected value. %s" % BUG_REPORT)

        return result
开发者ID:jpann,项目名称:Full30.bundle,代码行数:39,代码来源:__init__.py


示例17: fild_all_files

import os
import execjs
import simplejson

from models import Entry, Serializer

APP_TAG = 'vscode'
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
I18N_DIR = os.path.join(SCRIPT_DIR, '../workspace/vscode/i18n')
OUTPUT_JSON_PATH = os.path.join(SCRIPT_DIR, '../generated/vscode.json')

nodejs = execjs.get("Node")

def fild_all_files(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            s = os.path.join(root, file)
            yield os.path.join(root, file)

def main():
	pass

if '__main__' in __name__:
	main()
开发者ID:PyYoshi,项目名称:LangHints,代码行数:24,代码来源:vscode.py


示例18: not

import time
import re
import requests
from requests.adapters import HTTPAdapter
import execjs

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

DEFAULT_USER_AGENT = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36")

JS_ENGINE = execjs.get().name

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, V8, or PyV8." % JS_ENGINE)

class CloudflareAdapter(HTTPAdapter):
    def send(self, request, **kwargs):
        domain = request.url.split("/")[2]
        resp = super(CloudflareAdapter, self).send(request, **kwargs)

        # Check if we already solved a challenge
        if request._cookies.get("cf_clearance", domain="." + domain):
            return resp

        # Check if Cloudflare anti-bot is on
        if ( "URL=/cdn-cgi/" in resp.headers.get("Refresh", "") and
开发者ID:carriercomm,项目名称:cloudflare-scrape,代码行数:31,代码来源:__init__.py


示例19: _default_runtime

def _default_runtime():
    return execjs.get()
开发者ID:Xavura,项目名称:Python-CoffeeScript,代码行数:2,代码来源:__init__.py


示例20: require

import execjs

_node = execjs.get("Node")
_context = execjs.compile("""
    var twitter = require('twitter-text');
""")

get_tweet_length = lambda text, options: _context.call("twitter.getTweetLength", text, options)
开发者ID:themylogin,项目名称:twitter-overkill,代码行数:8,代码来源:twitter_text.py



注:本文中的execjs.get函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python execnet.makegateway函数代码示例发布时间:2022-05-24
下一篇:
Python execjs.compile函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap