[PyQt] sent javascript code when opening website
Robert Kent
rob at gulon.co.uk
Sat Mar 29 12:14:29 GMT 2014
Hi Peter,
Try the following code for your browser:
#!/usr/bin/env python
import re
import sip
sip.setapi('QVariant',2)
sip.setapi('QString',2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
class WebPage(QWebPage):
def __init__(self, parent=None, **kwargs):
QWebPage.__init__(self, parent, **kwargs)
self.useragent = "Mozilla/4.0 (compatible; MSIE 7.0; Linux)"
def setUserAgent(self, agent):
if agent=="default": self.useragent = "Mozilla/5.0 (Linux; U; Linux;
en-US; rv:1.9.2.28) Gecko/20120306 Firefox/3.6.28"
else: self.useragent = agent
def userAgentForUrl(self, url): return self.useragent
class MainWindow(QMainWindow):
def __init__(self, url, parent=None, **kwargs):
QMainWindow.__init__(self, parent, **kwargs)
self._url=url
self._regexps={
'cookie':
re.compile(r'(?P<cookie_name>\S*?)\s*=\s*(?P<cookie_value>\S*?);', re.I |
re.DOTALL)
}
cookieBase=QNetworkCookie("", "")
self._cookies=cookieBase.parseCookies("")
cookieInput="acookie=a; bcookie=b; ccookie=c;"
for name,value in self._regexps['cookie'].findall(cookieInput):
self._cookies.append(QNetworkCookie(name,value))
self._cookieJar=QNetworkCookieJar(self)
self._networkManager=QNetworkAccessManager(self)
self._networkManager.setCookieJar(self._cookieJar)
self._networkManager.sslErrors.connect(self.onSslErrors)
self._webPage=WebPage(self)
self._webPage.setUserAgent('default')
self._webPage.setNetworkAccessManager(self._networkManager)
self._webView=QWebView(self, loadFinished=self.loadFinished)
self._webView.setPage(self._webPage)
self._webView.settings().setAttribute(QWebSettings.PluginsEnabled,True)
self._webView.load(QUrl(self._url))
self.setCentralWidget(self._webView)
@pyqtSlot(QNetworkReply, list)
def onSslErrors(self, reply, errors):
url=reply.url().toString()
reply.ignoreSslErrors()
print "SSL certificate error ignored: %s" % url
@pyqtSlot(bool)
def loadFinished(self, ok):
if not ok: return
self._webPage.mainFrame().evaluateJavaScript('alert("Hello!");')
if __name__ == "__main__":
from sys import argv, exit
a=QApplication(argv)
m=MainWindow("http://www.facebook.com/")
m.show()
m.raise_()
exit(a.exec_())
I've restructured and tidied up your example a little, but it still does the
same thing. The part I've added is executing JavaScript when the page is
loaded. I've connected a slot 'loadFinished' to the QWebView's signal of the
same name which calls the main frames 'evaluateJavaScript' method.
Hope this helps and does what you want,
Rob
From: Peter Irbizon <peterirbizon at gmail.com>
Date: Friday, 28 March 2014 23:58
To: <pyqt at riverbankcomputing.com>
Subject: [PyQt] sent javascript code when opening website
Hi it's me again :)
please how can I send javascript code when opening website with py below?
I need to execute function sample (){ alert('hello');} when site is loaded.
here is my python code for simple webbrowser:
#!/usr/bin/env pythonimport re
import sys
import PyQt4from PyQt4 import QtCore, QtGui ,QtWebKitfrom PyQt4 import uic
from PyQt4.QtCore import *from PyQt4.QtGui import *from PyQt4.QtWebKit
import *from PyQt4.QtNetwork import *from PyQt4.QtCore import SIGNAL, QUrl,
QString, Qt, QEventfrom PyQt4.QtCore import QSize, QDateTime, QPointfrom
PyQt4.QtGui import QApplication, QImage, QPainterfrom PyQt4.QtGui import
QCursor, QMouseEvent, QKeyEventfrom PyQt4.QtNetwork import QNetworkCookie,
QNetworkAccessManagerfrom PyQt4.QtNetwork import QNetworkCookieJar,
QNetworkRequest, QNetworkProxyfrom PyQt4.QtWebKit import QWebPage, QWebView
class WebPage(QWebPage):
def __init__(self, user_agent):
QWebPage.__init__(self)
# set user agent
self.user_agent = user_agent
def userAgentForUrl(self, url):
#~ return self.user_agent
return QString(QByteArray(self.user_agent))
def javaScriptAlert(self, frame, message):
"""Override default javascript alert popup
"""
print 'Alert:', message
class IEWinApp:
def __init__(self,url):
self.url=url
self.REGEXPS = \
{
'cookie':re.compile(r'(?P<cookie_name>\S*?)\s*=\s*(?P<cookie_value>\S*?);',
re.I | re.DOTALL)
}
cookie_input = "acookie=a; bcookie=b; ccookie=c;"
#~ self.current = "http://www.useragentstring.com/"
cookiebase = QNetworkCookie("","")
self.cookies = cookiebase.parseCookies("")
for cookiename,cookievalue in
self.REGEXPS['cookie'].findall(cookie_input):
cookie_tmp =
QNetworkCookie(QByteArray(cookiename),QByteArray(cookievalue))
self.cookies.append(cookie_tmp)
self.cookiejar = QNetworkCookieJar()
#~ self.cookiejar.setCookiesFromUrl(self.cookies, QUrl(self.current))
self.network_manager = QNetworkAccessManager()
self.network_manager.setCookieJar(self.cookiejar)
self.network_manager.sslErrors.connect(on_ssl_errors)
#~ self.window = WebBrowser()
self.page = IEWinPage()
#~ agent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)1"
agent="default"
self.page.setUserAgent(agent)
self.page.setNetworkAccessManager(self.network_manager)
self.frame = self.page.mainFrame()
#~ self.window.webView.setPage(self.page)
self.webView=QWebView()
self.webView.setPage(self.page)
self.webView.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled,Tr
ue)
#~ self.frame.load(QUrl(self.current))
self.webView.load(QUrl(self.url))
#~ self.window.show()
self.webView.show()def on_ssl_errors(reply, errors):
url = unicode(reply.url().toString())
reply.ignoreSslErrors()
print "SSL certificate error ignored: %s" % url
class IEWinPage(QWebPage):
def __init__(self):
QWebPage.__init__(self)
self.useragent = "Mozilla/4.0 (compatible; MSIE 7.0; Linux)"
def setUserAgent(self, agent):
if agent=="default":
self.useragent = "Mozilla/5.0 (Linux; U; Linux; en-US;
rv:1.9.2.28) Gecko/20120306 Firefox/3.6.28"
else:
self.useragent = agent
def userAgentForUrl(self, url):
return QString(QByteArray(self.useragent))if __name__ == "__main__":
app = QApplication(sys.argv)
url= "http://facebook.com <http://facebook.com/> "
win = IEWinApp(url)
sys.exit( app.exec_() )
_______________________________________________ PyQt mailing list
PyQt at riverbankcomputing.com
http://www.riverbankcomputing.com/mailman/listinfo/pyqt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20140329/770f785e/attachment-0001.html>
More information about the PyQt
mailing list