Python, PyV8로 javascript 실행하기

파이썬에서 웹크롤링을 하다보면 자바스크립트로 데이터를 가져올때가 종종있다

PyV8은 구글에서 개발한 자바스크립트 엔진, V8을 파이썬에서 실행할수 있도록 한 라이브러리이다.

자바스크립트를 실행하고 결과를 Python으로 전달한다.

 

https://code.google.com/archive/p/pyv8/downloads

 

pip를 통해서도 설치할 수 있다.

-. 간단 사용 방법

import PyV8
ctxt = PyV8.JSContext() #PyV8 사용 준비
ctxt.enter()
ctxt.eval('var i = 1 + 2;')
print ctxt.eval('i;')

>>> 3

 

-. locals

PyV8은 자바스크립트를 실행하면서 생성된 모든 변수를 locals 클래스에 보관을 하고 있다.

import PyV8
ctxt = PyV8.JSContext() #PyV8 사용 준비
ctxt.enter()
ctxt.eval('var x = 1;')
ctxt.eval('var y = 2;')
ctxt.eval('var z = x + y;')

print ctxt.locals.keys()

>>> ['x', 'y', 'z']

 

-. 사용 예

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

# -*- encoding:utf8 -*-
# Python version in the development environment 2.7.11
import os,sys,time
os.chdir(os.path.dirname(__file__))
import PyV8

# 테스트에 사용할 javascript 함수
js = '''
function Hello() {
    document.write("hello, Python!!!")
}'''

class MockDocument(object): #Python에는 없는 document 객체를 처리하기 위해 Mock object를 생성
    def __init__(self):
        self.value = ''
    def write(self,*args): #document.write 처리용 method
        self.value += ''.join(str(t) for t in args)

class Global(PyV8.JSClass): #PyV8 문맥에서 javascript와 함께 사용이 가능한 Global 클래스 선언
    def __init__(self):
        self.document = MockDocument() # document 객체 처리

scope = Global()
ctxt = PyV8.JSContext(scope)
ctxt.enter()
ctxt.eval(js) #javascript 실행

ctxt.eval('Hello();')
print scope.document.value

>>> hello, Python!!!

 

위 처럼 PyV8을 이용하면 Python으로도 javascript를 실행할수가 있다.

 

참조사이트

http://blog.naver.com/powerhw/220262351769

http://stackoverflow.com/questions/10136319/executing-javascript-from-python

http://blog.naver.com/PostView.nhn?blogId=wwwkasa&logNo=220354387402&parentCategoryNo=&categoryNo=58&viewDate=&isShowPopularPosts=false&from=postView

http://www.hanul93.com/kicomav-pyv8/

https://pypi.python.org/pypi/PyV8

 

[출처] http://blog.naver.com/PostView.nhn?blogId=dudwo567890&logNo=220895234080&parentCategoryNo=&categoryNo=39&viewDate=&isShowPopularPosts=false&from=section

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
252 파이썬-sql알케미-tutorial, sqlalchemy tutorial file 졸리운_곰 2018.08.27 185
251 Data Structures and Algorithm In python 파이썬으로 자료구조와 알고리즘 : 출처 인터넷 file 졸리운_곰 2018.08.27 315
250 Mastering Basic Algorithms in the Python Language 이북 출처 인터넷 file 졸리운_곰 2018.08.27 381
249 텐서플로우-#1 자료형의 이해 file 졸리운_곰 2018.08.15 272
248 How to build a simple neural network in 9 lines of Python code file 졸리운_곰 2018.08.14 294
247 node.js python-shell을 활용하여 python 실행 file 졸리운_곰 2018.08.14 365
» Python, PyV8로 javascript 실행하기 file 졸리운_곰 2018.08.14 221
245 파이썬 플라스크 프레임워크 소개 졸리운_곰 2018.08.03 130
244 주피터(jupyter notebook) 원격 접속 file 졸리운_곰 2018.07.10 142
243 Pycharm 원격 서버 연결하기 file 졸리운_곰 2018.07.10 249
242 The Ultimate Flask Front-End – Part 2 file 졸리운_곰 2018.06.22 85
241 The Ultimate Flask Front-End file 졸리운_곰 2018.06.22 139
240 Django + djangorestframework + django_rest_swagger 시작 file 졸리운_곰 2018.05.27 65
239 Does Python SciPy need BLAS? 졸리운_곰 2018.05.26 85
238 PyCharm과 함께 DJango와 RestFramework를 활용한 웹 사이트 구축하기 file 졸리운_곰 2018.05.22 192
237 Flask-RESTPlus에서 REST API와 Swagger 문서를 통합 file 졸리운_곰 2018.05.22 353
236 Building beautiful REST APIs using Flask, Swagger UI and Flask-RESTPlus file 졸리운_곰 2018.05.22 263
235 [Python] Flask & flask-restplus && swagger ui file 졸리운_곰 2018.05.22 147
234 Django에서 MySQL DB를 연동하기 pycharm file 졸리운_곰 2018.04.10 427
233 Python Flask 로 간단한 REST API 작성하기 file 졸리운_곰 2018.04.07 226
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED