How to put result of JavaScript function into python variable. PyQt

2024/11/14 13:11:32

I want to make a function in PyQt evaluateJavaScript() (or may be similar one) and than display a result of evaluated function. Real function will be much bigger, and it might not be a string.

I'm only interesting in how to create a function inside PyQt code and than get the result into python variable.

To be more clear I will give you an example: that's the js that I want to type in after loadFinished on http://jquery.com:

w = document.getElementsByTagName('p')[0];
w.innerHTML

If I do it in browser console, I' will get an output:

"jQuery is a fast and concise JavaScript Library ...... blah blah blah"

And I want to store this output in a variable.

#!/usr/bin/env pythonfrom PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import os, sys, signal
from urllib2 import urlopenclass GBot(QWebView):def __init__(self):QWebView.__init__(self)self.setPage(BrowserSettings())#self.jquery = get_jquery()self.load(QUrl('http://jquery.com'))self.frame = self.page().currentFrame()def _loadFinished(self, ok):doc = self.frame.documentElement()#doc.evaluateJavaScript(self.jquery)r = doc.evaluateJavaScript('''w = document.getElementsByTagName('p')[0]; w.innerHTML''')print r #want to do something like thisif __name__ == '__main__':app = QApplication(sys.argv)bot = GBot()bot.show()if signal.signal(signal.SIGINT, signal.SIG_DFL):sys.exit(app.exec_())app.exec_()
Answer

In this example first I create a myWindow javascript object by passing self to the main frame, then call evaluateJavaScript when loadFinished:

#!/usr/bin/env python
#-*- coding:utf-8 -*-from PyQt4 import QtCore, QtGui, QtWebKit  getJsValue = """ 
w = document.getElementsByTagName('p')[0];
myWindow.showMessage(w.innerHTML);
"""  class myWindow(QtWebKit.QWebView):  def __init__(self, parent=None):super(myWindow, self).__init__(parent)self.page().mainFrame().addToJavaScriptWindowObject("myWindow", self)self.loadFinished.connect(self.on_loadFinished)self.load(QtCore.QUrl('http://jquery.com'))@QtCore.pyqtSlot(str)  def showMessage(self, message):print "Message from website:", message@QtCore.pyqtSlot()def on_loadFinished(self):self.page().mainFrame().evaluateJavaScript(getJsValue) if __name__ == "__main__":import sysapp = QtGui.QApplication(sys.argv)app.setApplicationName('myWindow')main = myWindow()main.show()sys.exit(app.exec_())
https://en.xdnf.cn/q/72328.html

Related Q&A

Wrap multiple tags with BeautifulSoup

Im writing a python script that allow to convert a html doc into a reveal.js slideshow. To do this, I need to wrap multiple tags inside a <section> tag. Its easy to wrap a single tag inside anoth…

How to permanently delete a file in python 3 and higher?

I want to permanently delete a file i have created with my python code. I know the os.remove() etc but cant find anything specific to delete a file permanently.(Dont want to fill Trash with unused file…

Django. Python social auth. create profiles at the end of pipeline

I want to add a function at the end of the auth pipeline, the function is meant to check if there is a "Profiles" table for that user, if there isnt it will create a table. The Profiles mode…

What is a good audio library for validating files in Python?

Im already checking for content-type, size, and extension (Django (audio) File Validation), but I need a library to read the file and confirm that it is in fact what I hope it is (mp3 and mp4 mostly).I…

Python 3.6+: Nested multiprocessing managers cause FileNotFoundError

So Im trying to use multiprocessing Manager on a dict of dicts, this was my initial try:from multiprocessing import Process, Managerdef task(stat):test[z] += 1test[y][Y0] += 5if __name__ == __main__:te…

Convert python disassembly from dis.dis back to codeobject

Is there any way to create code object from its disassembly acquired with dis.dis?For example, I compiled some code using co = compile(print("lol"), <string>, exec) and then printed di…

Loop over a tensor and apply function to each element

I want to loop over a tensor which contains a list of Int, and apply a function to each of the elements. In the function every element will get the value from a dict of python. I have tried the easy wa…

How to quickly get the last line from a .csv file over a network drive?

I store thousands of time series in .csv files on a network drive. Before I update the files, I first get the last line of the file to see the timestamp and then I update with data after that timestamp…

Force use of scientific style for basemap colorbar labels

String formatting can by used to specify scientific notation for matplotlib.basemap colorbar labels:cb = m.colorbar(cs, ax=ax1, format=%.4e)But then each label is scientifically notated with the base.I…

VS Code Doesnt Recognize Python Virtual Environment

Im using VS Code on a Mac to write Python code. Ive created a virtual environment named venv inside my project folder and opened VS Code in my project folder. I can see the venv folder in the Explore…