python使用PyV8执行javascript代码示例分享

yipeiwu_com5年前Python基础

安装相应的库,我使用的是PyV8

需要注意的是里面写的function函数需要用()括起来

复制代码 代码如下:

import PyV8

class Test():

      def js(self):       

   ctxt = PyV8.JSContext()       

   ctxt.enter()              

   func = ctxt.eval('''(function(){return '###'})''')       

   print func()       

   print '213'

if __name__ == '__main__':

     crawler = Test()   

  crawler.js()   

输出的结果是:

复制代码 代码如下:

>>>
###
213
>>>

向js代码中传递参数的方法

复制代码 代码如下:

  func = ctxt.eval(''' (function(a){return encodeURIComponent(a)})''')
        print func(a)

a是需要传递的参数,encodeURIComponent是js中的一种编码方式

我遇到这个问题是在做爬虫的时候,进行post传值的过程中,一些中文字符被网站的js使用encodeURIComponent进行了编码导致不能提交可识别的代码,所以想到这个办法在python程序中进行编码,之后再传值,就可以很好的解决这个问题

相关文章

pandas的相关系数与协方差实例

1、输出百分比变化以及前后指定的行数 a = np.arange(1,13).reshape(6,2) data = DataFrame(a) #计算列的百分比变化,如果...

py2exe 编译ico图标的代码

复制代码 代码如下: #setup.py from distutils.core import setup import py2exe setup( # targets to build...

Python获取时间戳代码实例

1、获取秒级时间戳与毫秒级时间戳、微秒级时间戳 import time import datetime t = time.time() print (t) #...

解决出现Incorrect integer value: '' for column 'id' at row 1的问题

解决出现Incorrect integer value: '' for column 'id' at row 1的问题 前言: 今天在学习Python的过程中操作数据库,遇到了一个问题,...

python定时器(Timer)用法简单实例

本文实例讲述了python定时器(Timer)用法。分享给大家供大家参考。具体如下: # encoding: UTF-8 import threading #Timer(定时器)是T...