class Browser(QObject): # pylint: disable=too-many-public-methods __execute_script_called = Signal(str) def __init__(self): super().__init__() self.app = QApplication([]) self.webview = QWebView() self.webview.setAttribute(Qt.WA_DeleteOnClose) self.webview.destroyed.connect(self.app.quit) self.__execute_script_called.connect(self.__execute_script) def __execute_script(self, javascript_code: str): assert current_thread_is_main() self.webview.page().mainFrame().evaluateJavaScript(javascript_code) def execute_script(self, javascript_code: str): if current_thread_is_main(): self.__execute_script(javascript_code) else: self.__execute_script_called.emit(javascript_code) def run(self, url): assert current_thread_is_main() self.webview.showFullScreen() self.webview.load(url) self.app.exec_()
class TextMediaView(MediaView): def __init__(self, media, parent): super(TextMediaView, self).__init__(media, parent) self.widget = QWebView(parent) self.widget.setGeometry(media['geometry']) self.set_default_widget_prop() self.widget.setDisabled(True) self.widget.page().mainFrame().setScrollBarPolicy( Qt.Vertical, Qt.ScrollBarAlwaysOff) self.widget.page().mainFrame().setScrollBarPolicy( Qt.Horizontal, Qt.ScrollBarAlwaysOff) @Slot() def play(self): self.finished = 0 path = '%s/%s_%s_%s.html' % (self.save_dir, self.layout_id, self.region_id, self.id) self.widget.load('file://' + path) self.widget.show() self.widget.raise_() if float(self.duration) > 0: self.play_timer.setInterval(int(float(self.duration) * 1000)) self.play_timer.start() self.started_signal.emit() @Slot() def stop(self, delete_widget=False): #---- kong ---- if not self.widget: return False super(TextMediaView, self).stop(delete_widget) return True
class HTMLApplication(object): def show(self): #It is IMPERATIVE that all forward slashes are scrubbed out, otherwise QTWebKit seems to be # easily confused kickOffHTML = join(dirname(__file__).replace('\\', '/'), "templates/index.html").replace('\\', '/') #This is basically a browser instance self.web = QWebView() #Unlikely to matter but prefer to be waiting for callback then try to catch # it in time. self.web.loadFinished.connect(self.onLoad) self.web.load(kickOffHTML) self.web.show() def onLoad(self): #This is the body of a web browser tab self.myPage = self.web.page() self.myPage.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) #This is the actual context/frame a webpage is running in. # Other frames could include iframes or such. self.myFrame = self.myPage.mainFrame() # ATTENTION here's the magic that sets a bridge between Python to HTML self.myFrame.addToJavaScriptWindowObject("eth", self.ethclient) #Tell the HTML side, we are open for business self.myFrame.evaluateJavaScript("ApplicationIsReady()")
class Browser: def __init__(self): self.network_manager = QNetworkAccessManager() self.network_manager.createRequest = self._create_request self.web_page = QWebPage() self.web_page.setNetworkAccessManager(self.network_manager) self.web_view = QWebView() self.web_view.setPage(self.web_page) self.html_data = None self.resultList = [] self.finished = threading.Event() def _create_request(self, operation, request, data): reply = QNetworkAccessManager.createRequest(self.network_manager, operation, request, data) self.resultList.append(request.url().toString()) return reply def myLoadFinish(self): #print "finished" self.finished.set() def getResourceUrlList(self, url): self.web_view.load(url) self.web_view.loadFinished.connect(self.myLoadFinish) self.finished.wait() return self.resultList
class TestJsCall(UsesQApplication): @classmethod def setUpClass(self): super(TestJsCall, self).setUpClass() def createInstance(self): global functionID self._view = QWebView() self._jsfuncs = JSFuncs() functionID = -1 self._view.page().mainFrame().addToJavaScriptWindowObject( "jsfuncs", self._jsfuncs) self._view.loadFinished[bool].connect(self.onLoadFinished) self._view.load(PAGE_DATA % FUNCTIONS_LIST[self._functionID]) self._view.show() def testJsCall(self): self._functionID = 0 self.createInstance() self.app.exec_() def onLoadFinished(self, result): global functionID self.assertEqual(self._functionID, functionID) if self._functionID == (len(FUNCTIONS_LIST) - 1): QTimer.singleShot(300, self.app.quit) else: #new test self._functionID += 1 self.createInstance()
class BaseWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.centralWidget = QtGui.QWidget() self.resize(800, 500) self.setWindowTitle('Test') self.tabs = QTabWidget() self.tabs.blockSignals(True) #just for not showing the initial message self.tabs.currentChanged.connect(self.onChange) #changed! self.webview = QWebView() self.webview.load(QUrl("http://gmx.de")) self.webview2 = QWebView() self.webview2.load(QUrl("http://web.de")) centralLayout = QtGui.QVBoxLayout() centralLayout.addWidget(self.tabs, 1) self.tabs.addTab(self.webview, "gmx") self.tabs.addTab(self.webview2, "web") self.centralWidget.setLayout(centralLayout) self.setCentralWidget(self.centralWidget) self.tabs.blockSignals(False) #now listen the currentChanged signal #@pyqtSlot() def onChange(self,i): #changed! QtGui.QMessageBox.information(self, "Tab Index Changed!", "Current Tab Index: %d" % i ) #changed!
class AssistantWindow(QtGui.QDialog): def __init__(self, *args, **kwargs): super(AssistantWindow, self).__init__(*args, **kwargs) self.smap = QWebView() self.lattitude = QtGui.QLineEdit() self.longitude = QtGui.QLineEdit() self.get_map_button = QtGui.QPushButton('Get map') self.get_map_button.clicked.connect(self.get_map) self.zoom_level = QtGui.QLineEdit() self.zoom_level.setText('18') self.flayout = QtGui.QFormLayout() self.setLayout(self.flayout) self.flayout.addRow('Lattitude:', self.lattitude) self.flayout.addRow('Longitude:', self.longitude) self.flayout.addRow('Zoom level:', self.zoom_level) self.flayout.addRow(self.get_map_button) self.flayout.addRow(self.smap) def get_map(self): lt = int(self.lattitude.text()) ln = int(self.longitude.text()) lt_g = coord_conv(lt) ln_g = coord_conv(ln) url = (ST_MAPS_API + 'center=%s,%s' % (lt_g, ln_g) + '&zoom=%s' % self.zoom_level.text() + '&size=400x400&sensor=false&maptype=hybrid' + '&markers=%s,%s' % (lt_g, ln_g)) self.smap.load(url)
def browse(url, name='', icon=''): from PySide.QtGui import QApplication, QIcon from PySide.QtCore import QUrl from PySide.QtWebKit import QWebView for try_ in range(10): try: assert urllib2.urlopen(url).code == 200 except (AssertionError, urllib2.URLError): time.sleep(0.25) else: print "Started Qt Web View after %i ticks." % try_ break else: sys.exit("Error initializing Qt Web View.") qtapp = QApplication(name) web = QWebView() web.load(QUrl(url)) if icon: print "Setting Icon to", icon web.setWindowIcon(QIcon(icon)) else: print "WARNING: No icon found in settings.py" web.setWindowTitle(name) web.show() qtapp.exec_()
class Robot(object): def __init__(self): self.view = QWebView() self.page = self.view.page() def start(self): self.view.show() QtCore.QObject.connect(self.view, QtCore.SIGNAL("loadFinished(bool)"), self.loaded) self.view.load(QUrl('https://login.yahoo.com/config/login_verify2?&.src=ym')) def loaded(self): url = self.view.url().toString() self.view.show() print "Loading %s finished" % url frame = self.page.mainFrame() els = frame.findAllElements("a[id*='copyright']") for i in range(els.count()): print 'Plain Text [%s]' % els.at(i).toPlainText().encode('utf8','ignore') print 'inner xml %s' % els.at(i).toInnerXml() child_els = els.at(i).findAll('*') for j in range(child_els.count()): print 'childs inner xml [%s] ' % child_els.at(j).toInnerXml()
class TestJsCall(UsesQApplication): @classmethod def setUpClass(self): super(TestJsCall, self).setUpClass() def createInstance(self): global functionID self._view = QWebView() self._jsfuncs = JSFuncs() functionID = -1 self._view.page().mainFrame().addToJavaScriptWindowObject("jsfuncs", self._jsfuncs) self._view.loadFinished[bool].connect(self.onLoadFinished) self._view.load(PAGE_DATA % FUNCTIONS_LIST[self._functionID]) self._view.show() def testJsCall(self): self._functionID = 0 self.createInstance() self.app.exec_() def onLoadFinished(self, result): global functionID self.assertEqual(self._functionID, functionID) if self._functionID == (len(FUNCTIONS_LIST) - 1): QTimer.singleShot(300, self.app.quit) else: #new test self._functionID += 1 self.createInstance()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() # 创建QEventLoop对象,该对象用于创建本地时间循环 webview.loadFinished.connect(loop.quit) # QWebView对象的loadFinished回调连接了QEventLoop的quit方法,从而可以在网页加载完成之后停止事件循环 webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() # QwebView的加载方法是异步的,执行过程会在网页加载时立即传入下一行, # 但我们希望等待网页加载完成,因此需要在事件循环启动时调用loop.exec_() webview.show() # 调用QWebViewGUI的show()方法来显示渲染窗口,以方便调试 frame = webview.page().mainFrame() # 创建一个指代框架的变量 # 使用CSS模式在框架中定位元素,然后设置搜索参数 frame.findFirstElement('#search_term').setAttribute('Value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') # 使用evaluate JavaScript()方法提交事件,模拟点击事件 frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_() # 进入应用的事件循环,可以对表单操作进行复查,如果没有使用该方法,脚本就会直接结束 # 等待结果,三种方法处理: # 1、等待一定时间,期望AJAX事件能够在此时刻之前完成 # 2、重写Qt的网络管理器,跟踪URL请求完成的事件 # 3、轮询网页,等待特定内容出现,下面采用第三种方法 elements = None while not elements: app.processEvents() # 用于给Qt事件循环执行任务的事件,比如响应点击事件和更新GUI elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
def webkit_download(url): app = QApplication([]) webview = QWebView() webview.loadFinished.connect(app.quit) webview.load(url) app.exec_() # delay here until download finished return webview.page().mainFrame().toHtml()
def get_site_text(url='https://test.api.unistream.com/help/index.html'): """Функция возвращает содержимое по указанному url.""" import sys from PySide.QtGui import QApplication from PySide.QtCore import QEventLoop from PySide.QtWebKit import QWebSettings, QWebPage, QWebView from PySide.QtNetwork import QNetworkProxyFactory # Чтобы не было проблем запуска компов с прокси: QNetworkProxyFactory.setUseSystemConfiguration(True) QWebSettings.globalSettings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) class WebPage(QWebPage): def userAgentForUrl(self, url): return 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0' if QApplication.instance() is None: QApplication(sys.argv) view = QWebView() view.setPage(WebPage()) view.load(url) # Ждем пока прогрузится страница loop = QEventLoop() view.loadFinished.connect(loop.quit) loop.exec_() doc = view.page().mainFrame().documentElement() print(len(doc.toOuterXml()), len(doc.toPlainText())) return doc.toPlainText()
def initUI(self): hbox = QtGui.QVBoxLayout() #hbox.addStretch() plot_view = QWebView() self.page = _LoggedPage() #page.newData.connect(onNewData) self.page.commandRecieved.connect(self.commandRecieved) self.page.helpNeeded.connect(self.helpNeeded) self.page.tabPressed.connect(self.tabPressed) plot_view.setPage(self.page) #plot_path = 'test.html' dir_path = os.path.dirname(os.path.realpath(__file__)) plot_view.load(QUrl('file:///%s/ptty.html' % dir_path)) plot_view_settings = plot_view.settings() plot_view_settings.setAttribute(QWebSettings.WebGLEnabled, True) plot_view_settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) hbox.addWidget(plot_view) self.setLayout(hbox) self.setWindowTitle('WTerminal') self.show()
class HTMLApplication(object): def show(self): #It is IMPERATIVE that all forward slashes are scrubbed out, otherwise QTWebKit seems to be # easily confused kickOffHTML = join( dirname(__file__).replace('\\', '/'), "templates/index.html").replace('\\', '/') #This is basically a browser instance self.web = QWebView() #Unlikely to matter but prefer to be waiting for callback then try to catch # it in time. self.web.loadFinished.connect(self.onLoad) self.web.load(kickOffHTML) self.web.show() def onLoad(self): #This is the body of a web browser tab self.myPage = self.web.page() self.myPage.settings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) #This is the actual context/frame a webpage is running in. # Other frames could include iframes or such. self.myFrame = self.myPage.mainFrame() # ATTENTION here's the magic that sets a bridge between Python to HTML self.myFrame.addToJavaScriptWindowObject("eth", self.ethclient) #Tell the HTML side, we are open for business self.myFrame.evaluateJavaScript("ApplicationIsReady()")
def createWebView( nIndex ): global functionID global currentWebView functionID = nIndex currentWebView = QWebView() currentWebView._jsfuncs = JSFuncs() currentWebView.page().mainFrame().addToJavaScriptWindowObject("jsfuncs", currentWebView._jsfuncs) QObject.connect( currentWebView, QtCore.SIGNAL('loadFinished( bool )'), onLoadFinished ) currentWebView.load(PAGE_DATA % FUNCTIONS_LIST[ nIndex ]) currentWebView.show()
def new_tab(self): """Open new tab.""" tasklist = QTreeView() tasklist.hide() tasklist.setObjectName('taskList') tasklist.setMinimumWidth(100) tasklist.setMaximumWidth(250) new_tab = QWebView() new_tab.setObjectName('webView') inspector = QWebInspector(self) inspector.setObjectName('webInspector') inspector.hide() page_layout = QVBoxLayout() page_layout.setSpacing(0) page_layout.setContentsMargins(0, 0, 0, 0) page_layout.addWidget(new_tab) page_layout.addWidget(inspector) page_widget = QFrame() page_widget.setObjectName('pageWidget') page_widget.setLayout(page_layout) complete_tab_layout = QHBoxLayout() complete_tab_layout.setSpacing(0) complete_tab_layout.setContentsMargins(0, 0, 0, 0) complete_tab_layout.addWidget(tasklist) complete_tab_layout.addWidget(page_widget) complete_tab_widget = QFrame() complete_tab_widget.setLayout(complete_tab_layout) new_tab.load(QUrl(self.startpage)) self.tabs.setUpdatesEnabled(False) if self.new_tab_behavior == "insert": self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget, unicode(new_tab.title())) elif self.new_tab_behavior == "append": self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title())) self.tabs.setCurrentWidget(complete_tab_widget) self.tabs.setTabText(self.tabs.currentIndex(), unicode(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).title())) self.tabs.setUpdatesEnabled(True) # tab.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) # tab.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) new_tab.titleChanged.connect(self.change_tab) new_tab.urlChanged.connect(self.change_tab) new_tab.loadStarted.connect(self.load_start) new_tab.loadFinished.connect(self.load_finish) new_tab.loadProgress.connect(self.pbar.setValue) new_tab.page().linkHovered.connect(self.linkHover) inspector.setPage(new_tab.page())
def testPlugin(self): view = QWebView() fac = PluginFactory() view.page().setPluginFactory(fac) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) view.load(QUrl(os.path.join(os.path.abspath(os.path.dirname(__file__)), "qmlplugin", "index.html"))) view.resize(840, 600) view.show() QTimer.singleShot(500, self.app.quit) self.app.exec_()
def __init__(self): super(WebWindow,self).__init__() Loader = QUiLoader() uiFile = QFile("C:/Qt/Qt5.0.1/Tools/QtCreator/bin/ScriptAnalyzerNew/webview.ui") uiFile.open(QFile.ReadOnly) self.mainWindow = Loader.load(uiFile) WebV = QWebView() layout = QVBoxLayout() layout.addWidget(WebV) self.mainWindow.webW.setLayout(layout) WebV.load(QUrl("file:///C:/Users/Administrator/Desktop/demo.html"))
def main(): app = QApplication([]) view = QWebView() fac = PluginFactory() view.page().setPluginFactory(fac) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) view.load(QUrl(sys.argv[1])) view.resize(840, 600) view.show() return app.exec_()
def test_native(): #url = 'http://translate.google.com/translate_tts' url = 'http://translate.google.com/translate_tts?tl=ja' url = QUrl(url) url.addEncodedQueryItem('q', QUrl.toPercentEncoding(q)) print url.toString() update_web_settings() a = QApplication(sys.argv) w = QWebView() w.load(url) w.show() ret = a.exec_()
class Browser(object): def __init__(self): self.network_manager = QNetworkAccessManager() self.network_manager.createRequest = self._create_request self.network_manager.finished.connect(self._request_finished) self.web_page = QWebPage() self.web_page.setNetworkAccessManager(self.network_manager) self.web_view = QWebView() self.web_view.setPage(self.web_page) def _create_request(self, operation, request, data): print(data.readAll()) reply = QNetworkAccessManager.createRequest(self.network_manager, operation, request, data) return reply def _request_finished(self, reply): if not reply.error() == QNetworkReply.NoError: # request probably failed print(reply.error()) print(reply.errorString()) def _make_request(self, url): request = QNetworkRequest() request.setUrl(QUrl(url)) return request def _urlencode_post_data(self, post_data): post_params = QUrl() for (key, value) in post_data.items(): post_params.addQueryItem(key, unicode(value)) return post_params.encodedQuery() def perform(self, url, method='GET', post_data=dict()): request = self._make_request(url) if method == 'GET': self.web_view.load(request) else: encoded_data = self._urlencode_post_data(post_data) request.setRawHeader( 'Content-Type', QByteArray('application/x-www-form-urlencoded')) self.web_view.load(request, QNetworkAccessManager.PostOperation, encoded_data)
def convert_html_to_pdf(source, destination, page_size=QPrinter.Letter, print_format=QPrinter.PdfFormat, timeout=10000, app=None): """Converts an .html file at the source to a .pdf at the destination Any external files linked in the source file must be paths relative to the location of the source file itself. If building the html file dynamically, the rel_path function can be used to create proper relative paths using the .html location as the source location. The conversion is done using th ability of a QPrinter to print a QWebView to a PDF. This means we must have some Qt bindings, either PySide (default) or PyQt4 (5 support incoming?), but then are only limited by what the QWebView can display. While the intent is so print to a PDF, the format parameter is exposed so that this can be used to print directly to a printer or (if >=Qt4.2) PostScript format. If this is being used in a larger QApplication, we should only have one instance of QApplication, so pass the existing instance to the `app` parameter. """ if app is None: app = QApplication(sys.argv) view = QWebView() # We want to ensure the page was fully loaded before printing, so # we wait for the loadFinished event to fire. with wait_for_signal(view.loadFinished, timeout=timeout): # QUrl requires absolute path names view.load(QUrl.fromLocalFile(os.path.abspath(source))) # With the QWebView loaded, we now print to the destination PDF printer = QPrinter() printer.setPageSize(page_size) printer.setOutputFormat(print_format) printer.setOutputFileName(destination) view.print_(printer) # Exit the application app.exit()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') frame.findFirstElement('#search').evaluateJavaScript('this.click()') elements = None while not elements: app.processEvents()
class HTMLApplication(object): def __init__(self, index_file, bridge = None, parent = None): self.index_file = index_file self.bridge = bridge self.mainWindow = QMainWindow(parent) self.mainWindow.setWindowTitle("My hub") self.mainWindow.setFixedSize(290,550); #This is basically a browser instance self.web = QWebView() self.mainWindow.setCentralWidget(self.web); def show(self): #It is IMPERATIVE that all forward slashes are scrubbed out, otherwise QTWebKit seems to be # easily confused #Asyncronously loads the website, in the interim you could throw up a splash screen # but this is relatively quick so it might not be worth it. self.web.loadFinished.connect(self.onLoad) self.web.setPage(WebPage()) self.web.load(self.index_file) self.mainWindow.show() #self.web.show() def onLoad(self): self.myPage = self.web.page() self.myPage.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.myPage.setNetworkAccessManager(WKNetworkAccessManager()) self.myFrame = self.myPage.mainFrame() for name, obj in self.bridge.items(): self.myFrame.addToJavaScriptWindowObject(name, obj) self.myFrame.evaluateJavaScript("ApplicationIsReady();") def onReload(self): print "reloaded"
def testPlugin(self): view = QWebView() fac = PluginFactory() view.page().setPluginFactory(fac) QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) view.load( QUrl( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'qmlplugin', 'index.html'))) view.resize(840, 600) view.show() QTimer.singleShot(500, self.app.quit) self.app.exec_()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option').setPlainText('1000') #设置纯文本 frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_() elements = None while not elements: app.processEvents() elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
def convert_html_to_pdf( source, destination, page_size=QPrinter.Letter, print_format=QPrinter.PdfFormat, timeout=10000, app=None): """Converts an .html file at the source to a .pdf at the destination Any external files linked in the source file must be paths relative to the location of the source file itself. If building the html file dynamically, the rel_path function can be used to create proper relative paths using the .html location as the source location. The conversion is done using th ability of a QPrinter to print a QWebView to a PDF. This means we must have some Qt bindings, either PySide (default) or PyQt4 (5 support incoming?), but then are only limited by what the QWebView can display. While the intent is so print to a PDF, the format parameter is exposed so that this can be used to print directly to a printer or (if >=Qt4.2) PostScript format. If this is being used in a larger QApplication, we should only have one instance of QApplication, so pass the existing instance to the `app` parameter. """ if app is None: app = QApplication(sys.argv) view = QWebView() # We want to ensure the page was fully loaded before printing, so # we wait for the loadFinished event to fire. with wait_for_signal(view.loadFinished, timeout=timeout): # QUrl requires absolute path names view.load(QUrl.fromLocalFile(os.path.abspath(source))) # With the QWebView loaded, we now print to the destination PDF printer = QPrinter() printer.setPageSize(page_size) printer.setOutputFormat(print_format) printer.setOutputFileName(destination) view.print_(printer) # Exit the application app.exit()
def main(): app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/search')) loop.exec_() webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') frame.findFirstElement('#search').evaluateJavaScript('this.click()') elements = None while not elements: app.processEvents() elements = frame.findAllElements('#results a') countries = [e.toPlainText().strip() for e in elements] print countries
class BrowserRender(QWebView): def __init__(self, display=True): self.app = QApplication([]) self.view = QWebView() self.loop = QEventLoop() def open(self, url, timeout=60): self.view.loadFinished.connect(self.loop.quit) self.view.load(QUrl(url)) self.loop.exec_() self.view.show() def html(self): return self.view.page().mainFrame().toHtml() def find(self, pattern): return self.view.page().mainFrame().findAllElements(pattern) def attr(self, pattern, name, value): for e in self.find(pattern): e.setAttribute(name, value) def text(self, pattern, value): for e in self.find(pattern): e.setPlainText(value) def click(self, pattern): for e in self.find(pattern): e.evaluateJavaScript('this.click()') def wait_load(self, pattern, timeout=60): deadline = time.time() + timeout while time.time() < deadline: self.app.processEvents() matches = self.find(pattern) if matches: return matches print 'Wait load time out' def exec_(self): self.app.exec_()
def runner(args, index_path, out_dir): app = QApplication(sys.argv) frame = MainWindow() frame.setWindowTitle('hwp5view') frame.setMinimumWidth(400) url = fspath2url(index_path) url = QUrl(url) view = QWebView(frame) logger.info('Loading...') view.load(url) @view.loadFinished.connect def onLoadFinished(): frame.show() frame.setCentralWidget(view) app.exec_()
class WebMediaView(MediaView): def __init__(self, media, parent): super(WebMediaView, self).__init__(media, parent) self._widget = QWebView(parent) self._widget.setGeometry(media['_geometry']) self.set_default_widget_prop() self._widget.setDisabled(True) self._widget.page().mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) self._widget.page().mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) @Slot() def play(self): self._finished = 0 path = "%s/%s_%s_%s.html" % ( self._save_dir, self._layout_id, self._region_id, self._id ) self._widget.load("about:blank") if 'webpage' == str(self._type) and 'native' == str(self._render): url = self._options['uri'] self._widget.load(QUrl.fromPercentEncoding(url)) else: self._widget.load('file://' + path) self._widget.show() self._widget.raise_() self._play_timer.setInterval(int(float(self._duration) * 1000)) self._play_timer.start() self.started_signal.emit()
class WebMediaView(MediaView): def __init__(self, media, parent): super(WebMediaView, self).__init__(media, parent) self._widget = QWebView(parent) self._widget.setGeometry(media['_geometry']) self.set_default_widget_prop() self._widget.setDisabled(True) self._widget.page().mainFrame().setScrollBarPolicy( Qt.Vertical, Qt.ScrollBarAlwaysOff) self._widget.page().mainFrame().setScrollBarPolicy( Qt.Horizontal, Qt.ScrollBarAlwaysOff) @Slot() def play(self): self._finished = 0 path = "%s/%s_%s_%s.html" % (self._save_dir, self._layout_id, self._region_id, self._id) self._widget.load("about:blank") if 'webpage' == str(self._type) and 'native' == str(self._render): url = self._options['uri'] self._widget.load(QUrl.fromPercentEncoding(url)) else: self._widget.load('file://' + path) self._widget.show() self._widget.raise_() self._play_timer.setInterval(int(float(self._duration) * 1000)) self._play_timer.start() self.started_signal.emit()
class Web(QtGui.QWidget): def __init__(self): super(Web, self).__init__() global clear clear = lambda: os.system('cls') self.initUI() def initUI(self): # Plugin QWebSettings.globalSettings().setAttribute(QWebSettings.PluginsEnabled, True) self.b = QWebView() PGrupo = None PID = None Pregunta = input("Elige [ ID ] o [ GRUPO ] (Respeta mayúsculas) : ") if Pregunta == "GRUPO": clear() PGrupo = input("Escribe el nombre del [ GRUPO ] : ") self.b.load(QUrl("http://xat.com/"+PGrupo)) elif Pregunta == "ID": clear() PID = int(input("Escribe la [ID] : ")) self.b.load(QUrl("http://xat.com/web_gear?id="+PID)) else: print("Asi no idiota") return self.initUI() self.b.setWindowTitle('SearchXat') # Icon #self.b.setWindowIcon(QtGui.QIcon('icon.png')) self.b.show()
class ViewReportDet(QWidget): def __init__(self): QWidget.__init__(self) self.title = "报告" self.__path = None self.__service = ReportDetService() # report view self.__wid_display = QWebView() # buttons _wid_buttons = ViewButtons( [dict(id="refresh", name=u'更新'), dict(id="export", name=u'导出')]) _wid_buttons.align_back() # main layout _layout = QVBoxLayout() _layout.addWidget(self.__wid_display) _layout.addWidget(_wid_buttons) self.setLayout(_layout) _layout.setContentsMargins(0, 0, 0, 0) # connection def usr_refresh(self, p_path=None): if p_path is not None: self.__path = dict(path=p_path) report_path = self.__service.get_report_path(self.__path) self.__wid_display.load(report_path)
class Application(object): def show(self): self.battery = Battery() self.wifi = Wifi() self.url = QUrl("qt.html") self.web = QWebView() self.web.loadFinished.connect(self.onLoad) self.web.load(self.url) self.web.show() def onLoad(self): self.page = self.web.page() self.page.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) self.frame = self.page.mainFrame() self.frame.addToJavaScriptWindowObject("battery", self.battery) self.frame.addToJavaScriptWindowObject("wifi", self.wifi) self.frame.evaluateJavaScript("isReady()") self.wifi.loop.run()
def main(): ''' 首先设置搜索参数和模拟动作事件,获取在此参数和动作下搜索后得到的网页 然后在这网页下,获取数据 ''' app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/places/default/search')) loop.exec_() webview.show() ## 显示渲染窗口,,可以直接在这个窗口里面输入参数,执行动作,方便调试 frame = webview.page().mainFrame() ## 设置搜索参数 # frame.findAllElements('#search_term') ##寻找所有的search_term框,返回的是列表 # frame.findAllElements('#page_size option:checked') # ## 表单使用evaluateJavaScript()方法进行提交,模拟点击事件 # frame.findAllElements('#search') frame.findFirstElement('#search_term').setAttribute('value', '.') ##第一个search_term框 frame.findFirstElement('#page_size option:checked').setPlainText( '1000') ##第一个page_size框 ## 表单使用evaluateJavaScript()方法进行提交,模拟点击事件 frame.findFirstElement('#search').evaluateJavaScript( 'this.click()') ##第一个点击框 ## 轮询网页,等待特定内容出现 ## 下面不断循环,直到国家链接出现在results这个div元素中,每次循环都会调用app.processEvents() ##用于给QT事件执行任务的时间,比如响应事件和更新GUI elements = None while not elements: app.processEvents() elements = frame.findAllElements('#results a') ##查找下载网页内的所有a标签 countries = [e.toPlainText().strip() for e in elements] ##取出所有a标签内的文本内容 print countries
class qt_method(common_method): def create_browser(self): try: from PySide.QtCore import QUrl from PySide.QtGui import QApplication from PySide.QtWebKit import QWebView except ImportError: raise self.raise_error("You need python-pyside\nDownload: http://developer.qt.nokia.com/wiki/PySide_Binaries_Linux") self.app = QApplication(sys.argv) self.web = QWebView() self.web.load(QUrl(self.OAUTH_URL)) self.web.loadFinished[bool].connect(self.load_finished) self.web.show() self.app.exec_() def get_url(self): return self.web.url().toString() def destroy(self): self.web.close() self.app.exit()
class Browser(QWidget): def __init__(self): super(Browser, self).__init__() self.layout = QStackedLayout(self) self.frontView = QWebView(self) self.backView = QWebView(self) self.frontView.page().networkAccessManager().sslErrors.connect(self.onSslErrors) self.backView.page().networkAccessManager().sslErrors.connect(self.onSslErrors) self.hostname = os.uname()[1] self.layout.setStackingMode(QStackedLayout.StackAll) self.layout.addWidget(self.frontView) self.layout.addWidget(self.backView) self.commands = { 'help' : self.cmdHelp, 'refresh' : self.cmdRefresh, 'add' : self.cmdAdd, 'del' : self.cmdDel, 'list' : self.cmdList, 'zoom' : self.cmdZoom, 'fs' : self.cmdFs, 'exit' : self.cmdExit, 'next' : self.cmdNext, 'restart' : self.cmdRestart, 'upgrade' : self.cmdUpgrade, } self.timer = QTimer() self.timer.setSingleShot(False) self.sites = list() self.siteId = -1 self.socket = False url = QUrl("http://dmr.tokiogroup.com/rrs.php") self.sites.append(Site(url, 10, 1)) url = QUrl("http://dmr.tokiogroup.com/lastheard.php") self.sites.append(Site(url, 10, 1)) self.server = QTcpServer() self.server.listen(QHostAddress.Any, 4242) self.connect(self.server, SIGNAL("newConnection()"), self, SLOT("onConnection()")); self.connect(self.timer, SIGNAL("timeout()"), self, SLOT("goNext()")); self.goNext() self.goNext() def goNext(self): self.cmdNext(list()) def onConnection(self): self.socket = self.server.nextPendingConnection() self.socket.write(self.hostname + ' % ') self.connect(self.socket, SIGNAL("readyRead()"), self, SLOT("onDataReceived()")); def print_(self, text): if (self.socket != False): self.socket.write(text + '\n') print(text) def onDataReceived(self): data = self.socket.readAll().data().strip() try: args = data.split(' ') map(lambda x : x.strip(), args) self.commands.get(args[0])(args) except Exception: self.print_('>> syntax error') self.printCommandsList() if self.socket.isOpen(): self.socket.write(self.hostname + ' % ') def printCommandsList(self): self.print_('avaible commands:') for command in self.commands: self.print_(' ' + command) def onSslErrors(self, reply, errors): url = unicode(reply.url().toString()) reply.ignoreSslErrors() # commands def cmdHelp(self, args): self.print_('>> help') self.printCommandsList() def cmdRefresh(self, args): self.print_('>> refresh ' + self.url.toString().encode()) self.frontView.reload() def cmdAdd(self, args): self.print_('>> add ' + args[1] + ' ' + args[2] + ' ' + args[3]) self.sites.append(Site(QUrl(args[1]), int(args[2], int(args[3])))) def cmdDel(self, args): self.print_('>> del ' + args[1]) self.sites.pop(int(args[1])) def cmdList(self, args): self.print_('>> list') self.print_('current list:') sitesCount = len(self.sites) i = 0 while i < sitesCount: self.print_('%1c[%1d] %2ds : %3s' % ((i==self.siteId) and '*' or ' ' ,i, self.sites[i].time, self.sites[i].url.toString().encode())) i = i + 1 def cmdZoom(self, args): self.print_('>> zoom ' + args[1]) self.frontView.setZoomFactor(float(args[1])) def cmdFs(self, args): self.print_('>> fs ' + args[1]) if (args[1] == '1'): self.showFullScreen() else: self.showNormal() def cmdExit(self, args): self.print_('>> exit') self.socket.close() def cmdNext(self, args): self.timer.stop() self.timer.start(self.sites[self.siteId].time * 1000) self.siteId = (self.siteId + 1) % len(self.sites) print('>> next ' + self.sites[self.siteId].url.toString().encode()) self.backView.show() self.frontView, self.backView = self.backView, self.frontView self.backView.load(self.sites[self.siteId].url) self.backView.setZoomFactor(self.sites[self.siteId].zoom) self.backView.hide() def cmdRestart(self, args): self.print_('>> restart') self.close() def cmdUpgrade(self, args): self.print_('>> upgrade') update = urllib.urlopen('https://raw.githubusercontent.com/tjardick/monitoring_browser/master/webkit.py').read() script = file('webkit.py', 'w') script.write(update) script.close() self.close()
# html = get_results(url, headers=headers) # parser = etree.XMLParser(recover=True) # tree = etree.fromstring(html,parser) # print(tree.cssselect('#result')[0].text) #初始化一个QApplication对象, app = QApplication([]) #创建一个QWebView对象,用于web文档的容器 webview = QWebView() # 创建一个QEventLoop对象,用于创建本地时间循环 loop = QEventLoop() # loadFinished回调连接了QEventLoop的quit方法,可以在网页加载完成之后停止事件循环 webview.loadFinished.connect(loop.quit) #将要加载的url传给QWebView,PyQt将该url的字符串封装在QUrl对象中 webview.load(QUrl(url)) # 等待网页加载完成,在事件循环启动时调用loop.exec_ loop.exec_() # 网页加载完成后退出事件循环 # html = webview.page().mainFrame().toHtml() # # 对加载的网页产生的HTMl进行数据抽取 # parser = etree.XMLParser(recover=True) # tree = etree.fromstring(html,parser) # print(tree.cssselect('#result')[0].text) webview.show() frame = webview.page().mainFrame() #找到id为search_term的标签,设置搜索值为.号(表示搜索全部结果)
class browserUI(QWidget): # 初期化関数 def __init__(self, parent=None): # スーパークラス(QWidget)のインスタンスメソッドからparentを使いたいのでsuper関数を使う super(browserUI, self).__init__(parent) self.setWindowFlags(Qt.WindowStaysOnTopHint) # 最善面表示 # self.setWindowFlags(Qt.FramelessWindowHint) # window枠の非表示 self.resize(600, 350) # サイズ変更 # タイトルの変更 self.setWindowTitle( QApplication.translate("Widget", "%s %s" % (__app_name__, __version__), None, QApplication.UnicodeUTF8)) # 背景の描画をOFF self.setAttribute(Qt.WA_TranslucentBackground, True) # CSSのセット # self.setCSS() # showUIメソッドの呼び出し self.showUI() def showUI(self): # レイアウトの作成 vbox = QVBoxLayout(self) # ブラウザの作成 self.browser = QWebView(self) # 動画観覧用にプラグインの許可 # self.browser.settings().setAttribute(QWebSettings.PluginsEnabled, True) # self.browser.settings().setAttribute(QWebSettings.AutoLoadImages, True) # self.browser.settings().setAttribute(QWebSettings.JavascriptEnabled, True) # Enable plugin/javascript/storage # webSetting = QWebSettings.globalSettings() # webSetting.setAttribute(QWebSettings.PluginsEnabled, True) # webSetting.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # webSetting.setAttribute(QWebSettings.JavascriptEnabled, True) # webSetting.setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) # webSetting.setAttribute(QWebSettings.LocalStorageEnabled, True) # プロキシの設定 # proxy = QNetworkProxy() # proxy.setType(QNetworkProxy.HttpProxy) # proxy.setType(QNetworkProxy.DefaultProxy) # proxy.setHostName("kwgproxya") # proxy.setPort(8080) # proxy.setUser("0160929") # proxy.setPassword("FFF2121098PBFFFpx12") # QNetworkProxy.setApplicationProxy(proxy) # self.browser.page().networkAccessManager().setProxy(proxy) # URLの設定 # self.browser.load(QUrl('http://localhost/Recomen/www/strong-player.html')) # self.browser.load(QUrl('https://www.youtube.com/watch?v=BDOiHSZ9g0E')) self.browser.load(QUrl('https://www.google.co.jp/')) # レイアウトにアタッチ vbox.addWidget(self.browser) # 親レイアウトに合わせて伸縮する設定 self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) def setCSS(self): """ 同じフォルダにあるcssを読みこんでセット """ with open("user-style.css", "r") as f: self.setStyleSheet("".join(f.readlines()))
def init_video(self): web = QWebView() web.showFullScreen() web.load(QUrl("http://www.google.com")) self.layout().addWidget(web)
QWebSettings.globalSettings().setAttribute(QWebSettings.WebAttribute.LocalContentCanAccessRemoteUrls, False) # Read game file f = open("wse/game.xml") xml = f.read() f.close(); wsehost.set("game.xml", xml) def add_js(): mainFrame.addToJavaScriptWindowObject("HOST", wsehost) mainFrame.evaluateJavaScript("if (!location.href.match(/^file:\/\//)) { HOST = undefined; }") @Slot(QUrl) def open_external_urls(url): QDesktopServices.openUrl(url) page.setLinkDelegationPolicy(QWebPage.DelegateAllLinks) wv.linkClicked.connect(open_external_urls) mainFrame.javaScriptWindowObjectCleared.connect(add_js) wv.load(QUrl("wse/index.html")) wv.show() #inspector.show() app.exec_()
def __init__(self, parent=None): """Initialize the parent class of this instance.""" super(window, self).__init__(parent) app.aboutToQuit.connect(self.myExitHandler) self.style_sheet = self.styleSheet('style') # app.setStyle(QStyleFactory.create('Macintosh')) #app.setStyleSheet(self.style_sheet) self.layout().setSpacing(0) self.layout().setContentsMargins(0,0,0,0) app.setOrganizationName("Eivind Arvesen") app.setOrganizationDomain("https://github.com/eivind88/raskolnikov") app.setApplicationName("Raskolnikov") app.setApplicationVersion("0.0.1") settings = QSettings() self.data_location = QDesktopServices.DataLocation self.temp_location = QDesktopServices.TempLocation self.cache_location = QDesktopServices.CacheLocation self.startpage = "https://duckduckgo.com/" self.new_tab_behavior = "insert" global bookmarks global saved_tabs print "Currently saved_tabs:\n", saved_tabs global menubar menubar = QMenuBar() # Initialize a statusbar for the window self.statusbar = self.statusBar() self.statusbar.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) self.statusbar.setStyleSheet(self.style_sheet) self.statusbar.setMinimumHeight(15) self.pbar = QProgressBar() self.pbar.setMaximumWidth(100) self.statusbar.addPermanentWidget(self.pbar) self.statusbar.hide() self.setMinimumSize(504, 235) # self.setWindowModified(True) # app.alert(self, 0) self.setWindowTitle("Raskolnikov") # toolbar = self.addToolBar('Toolbar') # toolbar.addAction(exitAction) # self.setUnifiedTitleAndToolBarOnMac(True) self.setWindowIcon(QIcon("")) # Create input widgets self.bbutton = QPushButton(u"<") self.fbutton = QPushButton(u">") self.hbutton = QPushButton(u"⌂") self.edit = QLineEdit("") self.edit.setFont(QFont("Helvetica Neue", 12, QFont.Normal)) self.edit.setPlaceholderText("Enter URL") # self.edit.setMinimumSize(400, 24) self.rbutton = QPushButton(u"↻") self.dbutton = QPushButton(u"☆") self.tbutton = QPushButton(u"⁐") # ↆ ⇧ √ ⌘ ⏎ ⏏ ⚠ ✓ ✕ ✖ ✗ ✘ ::: ❤ ☮ ☢ ☠ ✔ ☑ ♥ ✉ ☣ ☤ ✘ ☒ ♡ ツ ☼ ☁ ❅ ✎ self.nbutton = QPushButton(u"+") self.nbutton.setObjectName("NewTab") self.nbutton.setMinimumSize(35, 30) self.nbutton.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) self.edit.setTextMargins(2, 1, 2, 0) # create a horizontal layout for the input input_layout = QHBoxLayout() input_layout.setSpacing(4) input_layout.setContentsMargins(0, 0, 0, 0) # add the input widgets to the input layout input_layout.addWidget(self.bbutton) input_layout.addWidget(self.fbutton) input_layout.addWidget(self.hbutton) input_layout.addWidget(self.edit) input_layout.addWidget(self.rbutton) input_layout.addWidget(self.dbutton) input_layout.addWidget(self.tbutton) # create a widget to hold the input layout self.input_widget = QFrame() self.input_widget.setObjectName("InputWidget") self.input_widget.setStyleSheet(self.style_sheet) # set the layout of the widget self.input_widget.setLayout(input_layout) self.input_widget.setVisible(True) # CREATE BOOKMARK-LINE HERE self.bookmarks_layout = QHBoxLayout() self.bookmarks_layout.setSpacing(0) self.bookmarks_layout.setContentsMargins(0, 0, 0, 0) for i in bookmarks: link = QToolButton() link.setDefaultAction(QAction(unicode(i), link)) link.setObjectName(unicode(i)) link.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) link.clicked.connect(self.handleBookmarks) self.bookmarks_layout.addWidget(link) self.bookmarks_widget = QFrame() self.bookmarks_widget.setObjectName("BookmarkWidget") self.bookmarks_widget.setStyleSheet(self.style_sheet) self.bookmarks_widget.setLayout(self.bookmarks_layout) if not bookmarks: self.bookmarks_widget.hide() # Task list self.tasklist = QStandardItemModel() #parentItem = self.tasklist.invisibleRootItem() #self.tasklist.header().hide() self.tasklist.setHorizontalHeaderItem(0, QStandardItem('Tasks')) parentItem = QStandardItem("Parent") self.tasklist.appendRow(parentItem) for i in range(4): item = QStandardItem("Item %d" % i) parentItem.appendRow(item) #parentItem = item #self.list.activated[str].connect(self.handleBookmarks) #self.list.view().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) # create tabs self.tabs = QTabWidget() self.tabs.setDocumentMode(True) self.tabs.setTabsClosable(True) self.tabs.setMovable(True) self.tabs.tabBar().hide() self.tabs.setFont(QFont("Helvetica Neue", 11, QFont.Normal)) self.tabs.setCornerWidget(self.nbutton) self.tabs.cornerWidget().setObjectName("CornerWidget") self.tabs.cornerWidget().setMinimumSize(10, 24) self.tabs.cornerWidget().setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Minimum) if saved_tabs: for tab in saved_tabs['tabs']: tasklist = QTreeView() tasklist.hide() tasklist.setObjectName('taskList') tasklist.setMinimumWidth(100) tasklist.setMaximumWidth(250) new_tab = QWebView() new_tab.setObjectName('webView') inspector = QWebInspector(self) inspector.setObjectName('webInspector') inspector.hide() page_layout = QVBoxLayout() page_layout.setSpacing(0) page_layout.setContentsMargins(0, 0, 0, 0) page_layout.addWidget(new_tab) page_layout.addWidget(inspector) page_widget = QFrame() page_widget.setObjectName('pageWidget') page_widget.setLayout(page_layout) complete_tab_layout = QHBoxLayout() complete_tab_layout.setSpacing(0) complete_tab_layout.setContentsMargins(0, 0, 0, 0) complete_tab_layout.addWidget(tasklist) complete_tab_layout.addWidget(page_widget) complete_tab_widget = QFrame() complete_tab_widget.setLayout(complete_tab_layout) #for page in tab['history']: # new_tab.load(QUrl(page['url'])) #print tab['current_history'] #for item in new_tab.history().items(): # print item #new_tab.history().goToItem(new_tab.history().itemAt(tab['current_history'])) new_tab.load(QUrl(tab['history'][tab['current_history']]['url'])) tab['current_history'] self.tabs.setUpdatesEnabled(False) if self.new_tab_behavior == "insert": self.tabs.insertTab(self.tabs.currentIndex()+1, complete_tab_widget, unicode(new_tab.title())) elif self.new_tab_behavior == "append": self.tabs.appendTab(complete_tab_widget, unicode(new_tab.title())) self.tabs.setUpdatesEnabled(True) new_tab.titleChanged.connect(self.change_tab) new_tab.urlChanged.connect(self.change_tab) new_tab.loadStarted.connect(self.load_start) new_tab.loadFinished.connect(self.load_finish) new_tab.loadProgress.connect(self.pbar.setValue) new_tab.page().linkHovered.connect(self.linkHover) inspector.setPage(new_tab.page()) for index, tab in enumerate(saved_tabs['tabs']): self.tabs.setTabText(index, tab['history'][tab['current_history']]['title']) self.tabs.setCurrentIndex(saved_tabs['current_tab']) else: self.new_tab() tabs_layout = QVBoxLayout() tabs_layout.setSpacing(0) tabs_layout.setContentsMargins(0, 0, 0, 0) tabs_layout.addWidget(self.tabs) self.tabs_widget = QFrame() self.tabs_widget.setObjectName("TabLine") self.tabs_widget.setStyleSheet(self.style_sheet) self.tabs_widget.setLayout(tabs_layout) self.tabs_widget.setVisible(True) # Webkit settings gsettings = self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).settings().globalSettings() # Basic settings gsettings.setAttribute(QWebSettings.AutoLoadImages, True) gsettings.setAttribute(QWebSettings.JavascriptEnabled, True) gsettings.setAttribute(QWebSettings.JavascriptCanOpenWindows, False) gsettings.setAttribute(QWebSettings.JavascriptCanAccessClipboard, False) gsettings.setAttribute(QWebSettings.PluginsEnabled, False) # Flash isn't stable at present gsettings.setAttribute(QWebSettings.JavaEnabled, False) # Java applet's aren't supported by PySide gsettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) # Performace settings gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) gsettings.setAttribute(QWebSettings.AcceleratedCompositingEnabled, True) gsettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # Other settings gsettings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False) # Create a vertical layout and add widgets vlayout = QVBoxLayout() vlayout.setSpacing(0) vlayout.setContentsMargins(0, 0, 0, 0) # toolbar.addWidget(self.input_widget) vlayout.addWidget(self.input_widget) vlayout.addWidget(self.bookmarks_widget) vlayout.addWidget(self.tabs_widget) # create a widget to hold the vertical layout wrapper_widget = QWidget() wrapper_widget.setLayout(vlayout) self.setCentralWidget(wrapper_widget) self.bbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).back) self.fbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).forward) self.hbutton.clicked.connect(self.goHome) self.edit.returnPressed.connect(self.set_url) # Add button signal to "go" slot self.rbutton.clicked.connect(self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) self.dbutton.clicked.connect(self.bookmark) self.tbutton.clicked.connect(self.toggleTaskBar) self.nbutton.clicked.connect(self.new_tab) self.tabs.tabCloseRequested.connect(self.tabs.removeTab) self.tabs.currentChanged.connect(self.change_tab) widgets = (input_layout.itemAt(i).widget() for i in range( input_layout.count())) for widget in widgets: if isinstance(widget, QPushButton): widget.setFixedSize(33, 21) widget.setFont(QFont("Helvetica Neue", 12, QFont.Normal)) widget.pressed.connect(self.press_button) widget.released.connect(self.release_button) # make a ctrl+q quit sequence = QKeySequence(Qt.CTRL + Qt.Key_Q) QShortcut(sequence, self, SLOT("close()")) # make an accelerator to toggle fullscreen sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F) QShortcut(sequence, self, self.toggle_fullscreen) # make an accelerator to toggle input visibility sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_L) QShortcut(sequence, self, self.toggle_input) # make an accelerator to focus adress-bar sequence = QKeySequence(Qt.CTRL + Qt.Key_L) QShortcut(sequence, self, self.focus_adress) # make an accelerator to reload page sequence = QKeySequence(Qt.CTRL + Qt.Key_R) QShortcut(sequence, self, self.tabs.currentWidget().findChild(QFrame, unicode('pageWidget')).findChild(QWebView, unicode('webView')).reload) # make an accelerator to create new tab sequence = QKeySequence(Qt.CTRL + Qt.Key_T) QShortcut(sequence, self, self.new_tab) # make an accelerator to close tab sequence = QKeySequence(Qt.CTRL + Qt.Key_W) QShortcut(sequence, self, self.close_tab) # make an accelerator to navigate tabs sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Left) QShortcut(sequence, self, self.previous_tab) sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_Right) QShortcut(sequence, self, self.next_tab) # make an accelerator to toggle inspector sequence = QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_U) QShortcut(sequence, self, self.handleShowInspector) # make an accelerator to toggle bookmark sequence = QKeySequence(Qt.CTRL + Qt.Key_D) QShortcut(sequence, self, self.bookmark) # make an accelerator to toggle task/project-list sequence = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_L) QShortcut(sequence, self, self.toggleTaskBar) # finally set the attribute need to rotate # try: # self.setAttribute(Qt.WA_Maemo5AutoOrientation, True) # except: # print "not maemo" self.statusbar.show()
# -*- coding: utf-8 -*- from PySide.QtGui import QApplication from PySide.QtCore import QUrl, QEventLoop, QTimer from PySide.QtWebKit import QWebView import lxml.html app = QApplication([]) webview = QWebView() loop = QEventLoop() webview.loadFinished.connect(loop.quit) webview.load(QUrl('http://example.webscraping.com/search')) loop.exec_() ''' html = webview.page().mainFrame().toHtml() tree = lxml.html.fromstring(html) print tree.cssselect('#result')[0].text_content('1000')''' webview.show() frame = webview.page().mainFrame() frame.findFirstElement('#search_term').setAttribute('value', '.') frame.findFirstElement('#page_size option:checked').setPlainText('1000') frame.findFirstElement('#search').evaluateJavaScript('this.click()') app.exec_()
class Browser(object): def __init__(self, callback, logger, options=None): self.logger = logger self._request_ops = {'head': QNetworkAccessManager.HeadOperation, 'get': QNetworkAccessManager.GetOperation, 'put': QNetworkAccessManager.PutOperation, 'post': QNetworkAccessManager.PostOperation, 'delete': QNetworkAccessManager.DeleteOperation} self._network_manager = NetworkManager(logger) self._web_page = CraftyWebPage() self._web_page.setNetworkAccessManager(self._network_manager) self._web_view = QWebView() self._web_view.setPage(self._web_page) # connect the loadFinished signal to a method defined by us. # loadFinished is the signal which is triggered when a page is loaded self._web_view.loadFinished.connect(self._load_finished) options = options or dict() settings = self._web_view.settings() settings.setAttribute(QWebSettings.AutoLoadImages, options.pop('images', False)) settings.setAttribute(QWebSettings.JavascriptEnabled, options.pop('javascript', False)) settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, options.pop('popups', False)) settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, options.pop('private_browsing', False)) settings.setAttribute(QWebSettings.JavaEnabled, False) settings.setAttribute(QWebSettings.PluginsEnabled, False) settings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # store the callback function which will be called when a request is # finished self._result_callback = callback def _prepare_request(self, url, headers): # create an empty request request = QNetworkRequest() # assign a url to it request.setUrl(QUrl(url)) # add some custom headers to the request for (header_name, header_value) in headers.items(): request.setRawHeader(header_name, QByteArray(header_value)) return request def _urlencode_request_data(self, raw_data): # the data which we want to send to the server must be urlencoded request_data = QUrl() for (name, value) in raw_data.items(): request_data.addQueryItem(name, unicode(value)) return request_data.encodedQuery() def _load_finished(self, ok): """ Called when the page is fully loaded. It will get the html file of the loaded page and call the callback function with that result. """ frame = self._web_view.page().mainFrame() url = smart_str(frame.url().toString()) html = frame.toHtml() result = {'html': html, 'url': url, 'successful': True} if self._network_manager.errors: result['errors'] = self._network_manager.errors # calling the callback function which we passed upon instantiation to # report the results there self._result_callback(result) def make(self, method, url, headers, raw_data=None): request = self._prepare_request(url, headers) operation = self._request_ops[method.lower()] request_data = self._urlencode_request_data(raw_data or dict()) self._web_view.load(request, operation, request_data) def _find_element(self, selector): main_frame = self._web_page.mainFrame() element = main_frame.findFirstElement(selector) if element.isNull(): raise ElementNotFound(selector) return element def fill_input(self, selector, value): js_fill_input = """ this.setAttribute("value", "{0}"); this.value = "{0}"; """.format(value) element = self._find_element(selector) element.evaluateJavaScript(js_fill_input) def click(self, selector): element = self._find_element(selector) offset = element.geometry() js_click = """ function mouse_click(element) {{ var event = document.createEvent('MouseEvents'); var offsetX = {0} + 2; //add 2 pixels otherwise it would var offsetY = {1} - 2; //seem like we clicked on the margin event.initMouseEvent( 'click', //event type true, //canBubble true, //cancelable document.defaultView, //view 1, //detail (window.screenX + offsetX), //screenX - The coords within (window.screenY + offsetY), //screenY - the entire page offsetX, //clientX - The coords within offsetY, //clientY - the viewport false, //ctrlKey false, //altKey false, //shiftKey false, //metaKey 0, //0=left, 1=middle, 2=right element //relatedTarget ); element.dispatchEvent(event); //Fire the event }} mouse_click(this);""".format(offset.left(), offset.top()) element.evaluateJavaScript(js_click)
class Browser(object): def __init__(self, callback, logger, options=None): self.logger = logger options = options or dict() self._request_ops = {'head': QNetworkAccessManager.HeadOperation, 'get': QNetworkAccessManager.GetOperation, 'put': QNetworkAccessManager.PutOperation, 'post': QNetworkAccessManager.PostOperation, 'delete': QNetworkAccessManager.DeleteOperation} self._timeout = int(options.pop('timeout', 30)) * 1000 max_request_retries = options.pop('max_request_retries', 3) self._network_manager = SmartNetworkAccessManager(logger, max_request_retries) self._web_page = CraftyWebPage() self._web_page.setNetworkAccessManager(self._network_manager) self._web_view = QWebView() self._web_view.setPage(self._web_page) # connect the loadFinished signal to a method defined by us. # loadFinished is the signal which is triggered when a page is loaded self._web_view.loadFinished.connect(self._load_finished) settings = self._web_view.settings() settings.setAttribute(QWebSettings.AutoLoadImages, options.pop('images', False)) settings.setAttribute(QWebSettings.JavascriptEnabled, options.pop('javascript', False)) settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, options.pop('popups', False)) settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, options.pop('private_browsing', False)) settings.setAttribute(QWebSettings.JavaEnabled, False) settings.setAttribute(QWebSettings.PluginsEnabled, False) settings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # store the callback function which will be called when a request is # finished self._result_callback = callback self._is_task_finished = False self._destroyed_status = dict() def _prepare_request(self, url, headers): # create an empty request request = QNetworkRequest() # assign a url to it request.setUrl(QUrl(url)) # add some custom headers to the request for (header_name, header_value) in headers.items(): request.setRawHeader(header_name, QByteArray(header_value)) return request def _urlencode_request_data(self, raw_data): # the data which we want to send to the server must be urlencoded request_data = QUrl() for (name, value) in raw_data.items(): request_data.addQueryItem(name, unicode(value)) return request_data.encodedQuery() def _load_finished(self, ok): """ Called when the page is fully loaded. It will get the html file of the loaded page and call the callback function with that result. """ if self._is_task_finished: # in case loadFinished fires more than once and we already # reported back with a result, don't do that again self.logger.info('loadFinished emitted, but task was already ' 'finished.') return pending_requests = self._network_manager.active_requests if ok == 'timed_out': self.logger.info('loadFinished emitted, request timed out.') self._network_manager.errors.append('Request timed out.') # to avoid treating the request by the driver as successful ok = False elif len(pending_requests) > 0: self.logger.info("loadFinished emitted, waiting for requests:" " {0}".format(pending_requests)) loaded = partial(lambda x: self._load_finished(x), ok) QTimer.singleShot(1000, loaded) return self.logger.info('loadFinshed emitted, returning result.') frame = self._web_view.page().mainFrame() url = smart_str(frame.url().toString()) html = frame.toHtml() result = {'html': html, 'url': url, 'successful': ok} if self._network_manager.errors: result['errors'] = self._network_manager.errors self._finish_task(result) def _start_task(self): self._is_task_finished = False # abusing the ok param of loadFinished timed_out = lambda: self._load_finished('timed_out') self._timeout_timer = QTimer() self._timeout_timer.timeout.connect(timed_out) self._timeout_timer.start(self._timeout) def _finish_task(self, result): self._is_task_finished = True self._timeout_timer.stop() # calling the callback function which we passed upon instantiation to # report the results there self._result_callback(result) def make(self, method, url, headers, raw_data=None): request = self._prepare_request(url, headers) operation = self._request_ops[method.lower()] request_data = self._urlencode_request_data(raw_data or dict()) self._start_task() self._web_view.load(request, operation, request_data) def _find_element(self, selector): main_frame = self._web_page.mainFrame() element = main_frame.findFirstElement(selector) if element.isNull(): raise ElementNotFound(selector) return element def fill_input(self, selector, value): js_fill_input = """ this.setAttribute("value", "{0}"); this.value = "{0}"; """.format(value) element = self._find_element(selector) element.evaluateJavaScript(js_fill_input) def click(self, selector): element = self._find_element(selector) offset = element.geometry() js_click = """ function mouse_click(element) {{ var event = document.createEvent('MouseEvents'); var offsetX = {0} + 2; //add 2 pixels otherwise it would var offsetY = {1} - 2; //seem like we clicked on the margin event.initMouseEvent( 'click', //event type true, //canBubble true, //cancelable document.defaultView, //view 1, //detail (window.screenX + offsetX), //screenX - The coords within (window.screenY + offsetY), //screenY - the entire page offsetX, //clientX - The coords within offsetY, //clientY - the viewport false, //ctrlKey false, //altKey false, //shiftKey false, //metaKey 0, //0=left, 1=middle, 2=right element //relatedTarget ); element.dispatchEvent(event); //Fire the event }} mouse_click(this);""".format(offset.left(), offset.top()) self._start_task() element.evaluateJavaScript(js_click) def _destroyed(self, component): self._destroyed_status[component] = True if all(self._destroyed_status.values()): self._shutdown_callback() def shutdown(self, callback): self._shutdown_callback = callback self._web_view.stop() self._web_view.close() # will immediately stop any running javascript code self._web_view.settings().setAttribute(QWebSettings.JavascriptEnabled, False) # if any requests were started by javascript after loadFinished was # emitted, and before we stopped javascript execution, cancel them self._network_manager.abort_requests() self._destroyed_status['web_page'] = False self._web_page.destroyed.connect(lambda: self._destroyed('web_page')) self._web_page.deleteLater() self._destroyed_status['web_view'] = False self._web_view.destroyed.connect(lambda: self._destroyed('web_view')) self._web_view.deleteLater() self._destroyed_status['network_manager'] = False destroyer = lambda: self._destroyed('network_manager') self._network_manager.destroyed.connect(destroyer) self._network_manager.deleteLater()
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) #Validators for data input ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$") ipValidator = QRegExpValidator(self.leGraylogIP) ipValidator.setRegExp(ipRegex) self.leGraylogIP.setValidator(ipValidator) self.leGraylogPort.setValidator(QIntValidator(1, 65535)) self.leGraylogHttpPort.setValidator(QIntValidator(1, 65535)) ipValidator = QRegExpValidator(self.leAsterixIP) ipValidator.setRegExp(ipRegex) self.leAsterixIP.setValidator(ipValidator) self.leAsterixPort.setValidator(QIntValidator(1, 65535)) self.leAsterixSic.setValidator(QIntValidator(1, 256)) self.leIamodPort.setValidator(QIntValidator(1, 65535)) self.leIamodThreshold.setValidator(QIntValidator(0, 99999)) #Define functions for GUI actions self.pbStart.clicked.connect(self.__startServer) self.pbStop.clicked.connect(self.__stopServer) self.actionLicense.triggered.connect(self.__license) self.actionLoad_Config_File.triggered.connect(self.__dialogConfigFile) self.pbSaveConfiguration.clicked.connect(self.__writeConfigFile) self.pbStart.setEnabled(False) if self.__checkServerIsRunning(): self.__serverStatusImage(True) else: self.__serverStatusImage(False) self.configFile = ConfigParser.ConfigParser() self.view = QWebView() self.webLayout.addWidget(self.view) self.view.settings().setAttribute( QWebSettings.JavascriptCanOpenWindows, True) self.view.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.pbConnect.clicked.connect(self.__connectHttpServer) l = QVBoxLayout(self.tab2) sc = StaticCanvas(self.tab2, width=5, height=4, dpi=100) dc = DynamicCanvas(self.tab2, width=5, height=4, dpi=100) l.addWidget(sc) l.addWidget(dc) def __connectHttpServer(self): retCode = True retCode &= not self.leGraylogIP.text() retCode &= not self.leGraylogPort.text() if (not retCode): self.view.load( QUrl("http://" + self.leGraylogIP.text() + ":" + self.leGraylogHttpPort.text() + "/dashboards/59ef8317ac4207031e41f294")) self.view.show() else: QMessageBox.warning( self, "Error", "Please, fill Graylog IP and Http Port before connect!", QMessageBox.Ok) def __dialogConfigFile(self): self.configFileName = QFileDialog.getOpenFileName() self.__loadConfigFile() def __startServer(self): self.__serverStartStop('START') self.pbStop.setEnabled(True) self.pbStart.setEnabled(False) def __stopServer(self): self.__serverStartStop('STOP') self.pbStart.setEnabled(True) self.pbStop.setEnabled(False) def __license(self): '''Popup a box with about message.''' QMessageBox.about( self, "About PySide, Platform and the like", """<b>IAMOD Server GUI</b> {} <p>Copyright 2016, ICEA. <p>This file is part of atn-sim. <p>atn-sim is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. <p>atn-sim is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. <p>You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. <p>Python {} - PySide version {} - Qt version {} on {}""".format( __version__, platform.python_version(), PySide.__version__, PySide.QtCore.__version__, platform.system())) def __checkServerIsRunning(self): p = subprocess.Popen(["ps", "-aux"], stdout=subprocess.PIPE) out, err = p.communicate() if ('iamod_server' in out): return True else: return False def __serverStartStop(self, mode): scriptPath = __basePath__ + __packagePath__ + 'scripts/' iamodModule = 'br.gov.icea.server.iamod_server' if (mode == 'START'): if self.__checkServerIsRunning(): self.statusbar.showMessage("IAMOD Server is running") else: subprocess.Popen( scriptPath + "startServer.sh %s %s" % (str(iamodModule), str(self.configFileName[0])), shell=True) self.statusbar.showMessage("Start IAMOD Server") self.__serverStatusImage(True) self.__blockEditConfiguration(False) else: subprocess.Popen(scriptPath + "stopServer.sh", shell=True) self.statusbar.showMessage("Stop IAMOD Server") self.__serverStatusImage(False) self.__blockEditConfiguration(True) def __serverStatusImage(self, image): if image == True: self.statusImage.setPixmap(__basePath__ + __packagePath__ + '/gui/icons/serverOn.png') else: self.statusImage.setPixmap(__basePath__ + __packagePath__ + '/gui/icons/serverOff.png') def __blockEditConfiguration(self, block): self.gbConfiguration.setEnabled(block) def __loadConfigFile(self): fileName = self.configFileName[0] if (os.path.exists(fileName)): self.configFile.read(fileName) self.__readFile() self.pbStart.setEnabled(True) def __readFile(self): try: graylogIp = self.configFile.get("graylog", "server") except: graylogIp = "" try: graylogPort = self.configFile.get("graylog", "port") except: graylogPort = "" try: graylogHttpPort = self.configFile.get("graylog", "httpPort") except: graylogHttpPort = "" try: asterixIp = self.configFile.get("asterix", "server") except: asterixIp = "" try: asterixPort = self.configFile.get("asterix", "port") except: asterixPort = "" try: asterixSic = self.configFile.get("asterix", "sic") except: asterixSic = "" try: iamodPort = self.configFile.get("iamod", "port") except: iamodPort = "" try: iamodThreshold = self.configFile.get("iamod", "threshold") except: iamodThreshold = "" self.leGraylogIP.setText(graylogIp) self.leGraylogPort.setText(graylogPort) self.leGraylogHttpPort.setText(graylogHttpPort) self.leAsterixIP.setText(asterixIp) self.leAsterixPort.setText(asterixPort) self.leAsterixSic.setText(asterixSic) self.leIamodPort.setText(iamodPort) self.leIamodThreshold.setText(iamodThreshold) def __writeConfigFile(self): try: fileName = self.configFileName[0] except: fileName = "" if (not os.path.exists(fileName)): if (self.__validateForm()): self.configFileName = QFileDialog.getSaveFileName() else: QMessageBox.warning(self, "Error", "Please, fill all form before save!", QMessageBox.Ok) return cfgFile = open(self.configFileName[0], 'w') asterixIp = self.leAsterixIP.text() asterixPort = self.leAsterixPort.text() asterixSic = self.leAsterixSic.text() graylogIp = self.leGraylogIP.text() graylogPort = self.leGraylogPort.text() graylogHttpPort = self.leGraylogHttpPort.text() iamodPort = self.leIamodPort.text() iamodThreshold = self.leIamodThreshold.text() self.configFile.set("asterix", "server", asterixIp) self.configFile.set("asterix", "port", asterixPort) self.configFile.set("asterix", "sic", asterixSic) self.configFile.set("graylog", "server", graylogIp) self.configFile.set("graylog", "port", graylogPort) self.configFile.set("graylog", "httpPort", graylogHttpPort) self.configFile.set("iamod", "port", iamodPort) self.configFile.set("iamod", "threshold", iamodThreshold) self.configFile.write(cfgFile) def __validateForm(self): retCode = True retCode &= not self.leIamodThreshold.text() retCode &= not self.leIamodPort.text() retCode &= not self.leAsterixIP.text() retCode &= not self.leAsterixPort.text() retCode &= not self.leAsterixSic.text() retCode &= not self.leGraylogIP.text() retCode &= not self.leGraylogPort.text()
import sys from PySide.QtGui import QApplication from PySide.QtCore import QUrl from PySide.QtWebKit import QWebView app = QApplication(sys.argv) b = QWebView() b.load(QUrl("https://www.youtube.com/watch?v=rPCzao7H6n8")) b.show() app.exec_()
import sys from PySide.QtCore import * from PySide.QtGui import * from PySide.QtWebKit import QWebView app = QApplication(sys.argv) web = QWebView() web.showFullScreen() web.load(QUrl("http://www.google.com")) sys.exit(app.exec_())
class Browser(object): def __init__(self, callback, logger, options=None): self.logger = logger self._request_ops = {'head': QNetworkAccessManager.HeadOperation, 'get': QNetworkAccessManager.GetOperation, 'put': QNetworkAccessManager.PutOperation, 'post': QNetworkAccessManager.PostOperation, 'delete': QNetworkAccessManager.DeleteOperation} self._network_manager = NetworkManager(logger) self._web_page = QWebPage() self._web_page.setNetworkAccessManager(self._network_manager) self._web_view = QWebView() self._web_view.setPage(self._web_page) # connect the loadFinished signal to a method defined by us. # loadFinished is the signal which is triggered when a page is loaded self._web_view.loadFinished.connect(self._load_finished) options = options or dict() settings = self._web_view.settings() settings.setAttribute(QWebSettings.AutoLoadImages, options.pop('images', False)) settings.setAttribute(QWebSettings.JavascriptEnabled, options.pop('javascript', False)) settings.setAttribute(QWebSettings.JavascriptCanOpenWindows, options.pop('popups', False)) settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, options.pop('private_browsing', False)) settings.setAttribute(QWebSettings.JavaEnabled, False) settings.setAttribute(QWebSettings.PluginsEnabled, False) settings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) # store the callback function which will be called when a request is # finished self._result_callback = callback def _prepare_request(self, url, headers): # create an empty request request = QNetworkRequest() # assign a url to it request.setUrl(QUrl(url)) # add some custom headers to the request for (header_name, header_value) in headers.items(): request.setRawHeader(header_name, QByteArray(header_value)) return request def _urlencode_request_data(self, raw_data): # the data which we want to send to the server must be urlencoded request_data = QUrl() for (name, value) in raw_data.items(): request_data.addQueryItem(name, unicode(value)) return request_data.encodedQuery() def _load_finished(self, ok): """ Called when the page is fully loaded. It will get the html file of the loaded page and call the callback function with that result. """ frame = self._web_view.page().mainFrame() url = smart_str(frame.url().toString()) html = frame.toHtml() result = {'html': html, 'url': url, 'successful': ok} if self._network_manager.errors: result['errors'] = self._network_manager.errors # calling the callback function which we passed upon instantiation to # report the results there self._result_callback(result) def make(self, method, url, headers, raw_data=None): request = self._prepare_request(url, headers) operation = self._request_ops[method.lower()] request_data = self._urlencode_request_data(raw_data or dict()) self._web_view.load(request, operation, request_data)
#!/usr/bin/env python #-*- coding:utf-8 -*- # # Copyright (c) Collab. # See LICENSE.txt for details. import sys from PySide.QtCore import QUrl, QSize from PySide.QtGui import QApplication from PySide.QtWebKit import QWebView, QWebSettings app = QApplication(sys.argv) settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.DnsPrefetchEnabled, True) settings.setAttribute(QWebSettings.JavascriptEnabled, True) settings.setAttribute(QWebSettings.PluginsEnabled, True) settings.setAttribute(QWebSettings.AutoLoadImages, True) settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, False) settings.setAttribute(QWebSettings.LinksIncludedInFocusChain, True) settings.setFontSize(QWebSettings.DefaultFontSize, 16) settings.setFontSize(QWebSettings.DefaultFixedFontSize, 16) web = QWebView() web.load(QUrl("http://collab.com")) web.show() sys.exit(app.exec_())
QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True) # Телефон или емейл LOGIN = '******' PASSWORD = '******' URL = 'https://vk.com' if __name__ == '__main__': app = QApplication(sys.argv) view = QWebView() view.show() view.load(URL) loop = QEventLoop() view.loadFinished.connect(loop.quit) loop.exec_() doc = view.page().mainFrame().documentElement() email = doc.findFirst('#quick_email') password = doc.findFirst('#quick_pass') login_button = doc.findFirst('#quick_login_button') if email.isNull() or password.isNull() or login_button.isNull(): raise Exception('Ошибка при авторизации: не найдены поля емейла или пароля, или кнопка "Войти".') # Заполняем поля емейла/телефона и пароля