def urlChanged(self, qUrl): self.urlChanged = True url = qUrl.toString() # Some integrations/auth will get back to /services with no way to get back to chat if Resources.SERVICES_URL_RE.match(url): self.systemOpen(url) self.load(QUrl("https://" + qUrl.host() + "/messages/general")) else: self.settings().setUserStyleSheetUrl( QUrl.fromLocalFile(Resources.get_path("login.css"))) self.inject() # Save the loading team as default if url.endswith("/messages"): self.window.settings.setValue("Domain", 'https://' + qUrl.host())
def getwx(): global wxurl global wxreply print "getting current and forecast:" + time.ctime() wxurl = Config.wuprefix + ApiKeys.wuapi + \ '/conditions/astronomy/hourly10day/forecast10day/lang:' + \ Config.wuLanguage + '/q/' wxurl += str(Config.wulocation.lat) + ',' + \ str(Config.wulocation.lng) + '.json' wxurl += '?r=' + str(random.random()) print wxurl r = QUrl(wxurl) r = QNetworkRequest(r) wxreply = manager.get(r) wxreply.finished.connect(wxfinished)
def createDocument(self, filename, contents): """Create a new document using the specified filename and contents. Make it the current document in our mainwindow. """ while os.path.exists(filename) or app.findDocument( QUrl.fromLocalFile(filename)): filename = util.next_file(filename) doc = app.openUrl(QUrl()) doc.setPlainText(contents) doc.setUrl(QUrl.fromLocalFile(filename)) doc.setModified(True) self.mainwindow().setCurrentDocument(doc) return doc
def slot_file_new_from_template_action(action): name = action.objectName() d = app.openUrl(QUrl()) win = mainwindow() win.setCurrentDocument(d) from snippet import insert, snippets view = win.currentView() view.setFocus() insert.insert(name, view) d.setUndoRedoEnabled(False) d.setUndoRedoEnabled(True) # d.clearUndoRedoStacks() only in Qt >= 4.7 d.setModified(False) if 'template-run' in snippets.get(name).variables: import engrave engrave.engraver(win).engrave('preview', d)
def url2image(url, file_name=None): """Function at the specified url downloads the page and stores it QImage object and returns it. If you pass file_name, then the function will save the picture in the file. Функция по указанному url загружает страницу и сохраняет ее объект QImage и возвращает его. Если передать file_name, тогда функция сохранит в файл картинку. """ # Нужно создавать только один раз global qApp if qApp is None: qApp = QApplication([]) # Пришлось добавить из-за того, что картинки не прогружались load_pyqt4_plugins() # TODO: прятать вертикальный и горизонтальный ползунки # Загрузка url и ожидание ее view = QWebView() view.setPage(WebPage()) # view.show() view.load(QUrl(url)) loop = QEventLoop() view.loadFinished.connect(loop.quit) loop.exec_() # Запрашиваем через javascript размеры страницы сайта width = view.page().mainFrame().evaluateJavaScript( "window.document.body.scrollWidth") height = view.page().mainFrame().evaluateJavaScript( "window.document.body.scrollHeight") # Устанавливаем границы документа view.page().setViewportSize(QSize(width, height)) img = QImage(width, height, QImage.Format_ARGB32) painter = QPainter(img) painter.setRenderHint(QPainter.HighQualityAntialiasing) view.page().mainFrame().render(painter) painter.end() if file_name: img.save(file_name) # qApp.exec() return img
def open(self, address, method='get', headers={}, auth=None, wait_onload_event=True, wait_for_loading=True): """Opens a web page. :param address: The resource URL. :param method: The Http method. :param headers: An optional dict of extra request hearders. :param auth: An optional tupple of HTTP auth (username, password). :param wait_onload_event: If it's set to True waits until the OnLoad event from the main page is fired. Otherwise wait until the Dom is ready. :param wait_for_loading: If True waits until the page is Loaded. Note that wait_onload_event isn't valid if wait_for_loading is False. :return: Page resource, All loaded resources. """ if not wait_onload_event: if self.ghostInit.receivers(SIGNAL("dom_is_ready(bool)")) == 0: self.ghostInit.dom_is_ready.connect(self._page_loaded) Logger.log("Waiting until OnReady event is fired") else: if self.ghostInit.receivers(SIGNAL("dom_is_ready(bool)")) > 0: self.ghostInit.dom_is_ready.disconnect(self._page_loaded) #Logger.log("Waiting until OnLoad event is fired") body = QByteArray() try: method = getattr(QNetworkAccessManager, "%sOperation" % method.capitalize()) except AttributeError: raise Exception("Invalid http method %s" % method) request = QNetworkRequest(QUrl(address)) request.CacheLoadControl(QNetworkRequest.AlwaysNetwork) for header in headers: request.setRawHeader(header, headers[header]) if auth is not None: self.network_manager.setAuthCredentials(auth[0], auth[1]) self._reset_for_loading() self.main_frame.load(request, method, body) if not wait_for_loading: return self.get_loaded_page() return self.wait_for_page_loaded()
def load_url(self): ''' parse once url, first load it ''' global _CURRENT_URL_TYPE try: url = self.get_protected_iter.next() _CURRENT_URL_TYPE = 'protected' except StopIteration: try: url = self.get_gray_iter.next() _CURRENT_URL_TYPE = 'gray' except StopIteration: try: url = self.get_counterfeit_iter.next() _CURRENT_URL_TYPE = 'counterfeit' except StopIteration: try: url = self.get_monitor_iter.next() _CURRENT_URL_TYPE = 'monitor' except StopIteration: self.over_handle() global _CRAWLER_NUM run_time = int(time.time() - self.run_start_time) self.update_finish_state(_CRAWLER_NUM, run_time) os.remove(self.qt_live_path) os._exit(0) # 将实时运行状态写入防卡死检测文件 self.check_qt_alive.seek(0) # 清空文件 self.check_qt_alive.truncate(0) self.check_qt_alive.write(url + ' ' + str(_CRAWLER_NUM) + ' ' + str(self.engine_pid)) self.check_qt_alive.flush() local_html, local_time = self.web_save_path.get_html_path_abs( url, _CURRENT_URL_TYPE) global _LOCAL_TIME _LOCAL_TIME = local_time if local_html is None or local_time is None: sys.stdout.write('url not be saved: %s, task_id: %d\n' % (url, self.task_id)) self.load_url() else: global _CURRENT_URL global _CURRENT_TIME_PATH _CURRENT_URL = url _CURRENT_TIME_PATH = local_time #print 'load:', _CURRENT_URL self.load(QUrl(local_html))
def mainPyQt5(): # 必要なモジュールのimport from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEngineView url = 'https://github.com/tody411/PyIntroduction' app = QApplication(sys.argv) # QWebEngineViewによるWebページ表示 browser = QWebEngineView() browser.load(QUrl(url)) browser.show() sys.exit(app.exec_())
def createRequest(self, operation, request, outgoingData=None): try: url = request.url().toEncoded().data().decode('utf-8') if outgoingData is not None and type(outgoingData) == QIODevice: outgoingData = InterceptFormData(outgoingData) return StoreNetworkReply( self.framework, url, operation, request, outgoingData, self.cookieJar(), QNetworkAccessManager.createRequest(self, operation, request, outgoingData), self) except Exception as error: # exceptions will cause a segfault self.framework.report_exception(error) request.setUrl(QUrl('about:blank')) return QNetworkAccessManager.createRequest(self, operation, request, outgoingData)
def load(self): """ do the load and call fil_form """ if (self.address_to_process_index == 0): self.ui.result_box.setText("") print " we are in load with index being ", self.address_to_process_index, " ad address being ", self.address_to_search, " and we are going t call submit_form() " url = "https://hosturl/realEstate.jsp" self.ui.web_view.load(QUrl(url)) self.connect(self.ui.web_view, QtCore.SIGNAL("loadFinished(bool)"), self.submit_form) print " we are in load with index being ", self.address_to_process_index, " ad address being ", self.address_to_search, " and we are returning from load "
def update_content(self, item): if not item.data: self.clear() return html = "" for k in sorted(item.data): v = item.data[k] if v is not None: html += '<strong>%s</strong>: ' % k if isinstance(v, basestring): url = QUrl(v) if url.isValid() and url.scheme(): v = '<a href="%s">%s</a>' % (v, v) html += '%s<br>' % v self.setHtml(html)
def importItem(self, data): """Implement importing a new session from a json data dict.""" name = data['name'] session = sessions.sessionGroup(name) for key in data: if key == 'urls': urls = [] for u in data[key]: urls.append(QUrl(u)) session.setValue("urls", urls) elif key != 'name': session.setValue(key, data[key]) self.load() names = sessions.sessionNames() if name in names: self.setCurrentRow(names.index(name))
def __init__(self, URL, process=None): QWidget.__init__(self) BaseCentralWidget.__init__(self) self.path = URL self.process = process v_box = QVBoxLayout(self) #Web Frame self.webFrame = QWebView() self.webFrame.load(QUrl(URL)) v_box.addWidget(self.webFrame) if process is not None: time.sleep(0.5) self.webFrame.reload()
def __init__(self, url, app): global _cookieJar, cookie self._url = url self._app = app QWebPage.__init__(self) self.networkAccessManager().setCookieJar(_cookieJar) _cookieJar.setCookiesFromUrl(QNetworkCookie.parseCookies(_cookie), QUrl(url)) self.bind() self._app.exec_() self.user_agent_for_url = user_agent self.js_alert = alert self.js_prompt = alert self.js_confirm = alert self.js_console_message = console_message
def setKey(self, key, setFinished): @pyqtSlot(dict) def finished(response): self.access.finished.disconnect(finished) if response['isOk']: API_PlanetLabs.validKey = key response['data'].clear() del response['data'] del response['statusRequest'] setFinished(response) url = QUrl(API_PlanetLabs.urlRoot) self.access.finished.connect(finished) self.access.run(url, key, True) # Send all data in finished
def asyncFetchIssueCoverURLs(self, issue_id): self.issue_id = issue_id details = self.fetchCachedIssueSelectDetails(issue_id) if details['image_url'] is not None: self.urlFetchComplete.emit(details['image_url'], details['thumb_image_url'], self.issue_id) return issue_url = self.api_base_url + "/issue/" + CVTypeID.Issue + "-" + str( issue_id ) + "/?api_key=" + self.api_key + "&format=json&field_list=image,cover_date,site_detail_url" self.nam = QNetworkAccessManager() self.nam.finished.connect(self.asyncFetchIssueCoverURLComplete) self.nam.get(QNetworkRequest(QUrl(issue_url)))
def _manager_create_request(self, operation, request, data): url = unicode(request.url().toString()) operation_name = self._operation_names[operation].upper() self._debug(INFO, "Request: %s %s" % (operation_name, url)) for h in request.rawHeaderList(): self._debug(DEBUG, " %s: %s" % (h, request.rawHeader(h))) if self._url_filter: if self._url_filter(self._operation_names[operation], url) is False: self._debug(INFO, "URL filtered: %s" % url) request.setUrl(QUrl("about:blank")) else: self._debug(DEBUG, "URL not filtered: %s" % url) reply = QNetworkAccessManager.createRequest(self.manager, operation, request, data) return reply
def setUrl(self, url): """ Change the url for this document. """ if url is None: url = QUrl() old, self._url = self._url, url changed = old != url # number for nameless documents if self._url.isEmpty(): nums = [0] nums.extend(doc._num for doc in app.documents if doc is not self) self._num = max(nums) + 1 else: self._num = 0 if changed: self.urlChanged(url, old) app.documentUrlChanged(self, url, old)
def requestFetching(self, key): """ start fetching the repository given by key """ self.mRepositories[key]["state"] = 1 url = QUrl(self.mRepositories[key]["url"] + self.urlParams()) #v=str(QGis.QGIS_VERSION_INT) #url.addQueryItem('qgis', '.'.join([str(int(s)) for s in [v[0], v[1:3]]]) ) # don't include the bugfix version! self.mRepositories[key]["QRequest"] = QNetworkRequest(url) self.mRepositories[key]["QRequest"].setAttribute( QNetworkRequest.User, key) self.mRepositories[key]["xmlData"] = QgsNetworkAccessManager.instance( ).get(self.mRepositories[key]["QRequest"]) self.mRepositories[key]["xmlData"].setProperty('reposName', key) self.mRepositories[key]["xmlData"].downloadProgress.connect( self.mRepositories[key]["Relay"].dataReadProgress) self.mRepositories[key]["xmlData"].finished.connect(self.xmlDownloaded)
def __init__(self, url: str): self.app = QApplication(sys.argv) QWebPage.__init__(self) # noinspection PyUnresolvedReferences self.loadFinished.connect(self.on_page_load) self._error = None # Setup timeout timeout_value = 10 # seconds self.timeout_timer = QTimer() self.timeout_timer.timeout.connect(self._request_timed_out) self.timeout_timer.start(timeout_value * 1000) # Start the timer # load the page, timer running self.mainFrame().load(QUrl(url)) self.app.exec_()
def __searchVlastnici(self): """ """ jmeno = self.__forms.vlastnici.jmeno() rcIco = self.__forms.vlastnici.rcIco() lv = self.__forms.vlastnici.lv() sjm = self.__forms.vlastnici.isSjm() opo = self.__forms.vlastnici.isOpo() ofo = self.__forms.vlastnici.isOfo() url = QUrl( u"showText?page=search&type=vlastnici&jmeno={}&rcIco={}&sjm={}&opo={}&ofo={}&lv={}" .format(jmeno, rcIco, 1 if sjm else 0, 1 if opo else 0, 1 if ofo else 0, lv)) self.actionTriggered.emit(url)
def getwx(): global wxurl global wxreply print "getting current and forecast:" + time.ctime() wxurl = 'https://api.darksky.net/forecast/' + \ ApiKeys.dsapi + \ '/' wxurl += str(Config.location.lat) + ',' + \ str(Config.location.lng) wxurl += '?units=us&lang=' + Config.Language.lower() wxurl += '&r=' + str(random.random()) print wxurl r = QUrl(wxurl) r = QNetworkRequest(r) wxreply = manager.get(r) wxreply.finished.connect(wxfinished)
def getTiles(self, t, i=0): t = int(t / 600) * 600 self.getTime = t self.getIndex = i if i == 0: self.tileurls = [] self.tileQimages = [] for tt in self.tiletails: tileurl = "https://tilecache.rainviewer.com/v2/radar/%d/%s" \ % (t, tt) self.tileurls.append(tileurl) print self.myname + " " + str(self.getIndex) + " " + self.tileurls[i] self.tilereq = QNetworkRequest(QUrl(self.tileurls[i])) self.tilereply = manager.get(self.tilereq) QtCore.QObject.connect(self.tilereply, QtCore.SIGNAL("finished()"), self.getTilesReply)
def get_authorization_url(self, scopes): host, port = config.setting['server_host'], config.setting['server_port'] url = QUrl() if (host in MUSICBRAINZ_SERVERS and port == 80) or port == 443: url.setScheme("https") else: url.setScheme("http") if port != 80: url.setPort(port) url.setHost(host) url.setPath("/oauth2/authorize") url.addQueryItem("response_type", "code") url.addQueryItem("client_id", MUSICBRAINZ_OAUTH_CLIENT_ID) url.addQueryItem("redirect_uri", "urn:ietf:wg:oauth:2.0:oob") url.addQueryItem("scope", scopes) return str(url.toEncoded())
def __init__(self, parent=None, target=None, inventory=None): HelpProvider.__init__(self, parent) self.target = target if inventory is None: if is_url_local(self.target): inventory = os.path.join(self.target, "objects.inv") else: inventory = urljoin(self.target, "objects.inv") self.inventory = inventory self.islocal = bool(QUrl(inventory).toLocalFile()) self.items = None self._fetch_inventory()
def checkForNewReleases(self): """ Checks for new releases. :return: Method success. :rtype: bool """ if not self.__networkAccessManager.networkAccessible(): raise sibl_gui.exceptions.NetworkError( "{0} | Network is not accessible!".format( self.__class__.__name__)) self.__getReleasesFile( QUrl(os.path.join(self.__repositoryUrl, self.__releasesFileUrl))) return True
def __init__(self, view, results=[]): # an explicit reference to the provider has to be maintained # else a segfault ensues (collected prematurely I assume) self.img_provider = DocumentImageProvider() self.view = view # QDeclarativeView(self) self.results = results engine = self.view.engine() engine.addImageProvider('document_images', self.img_provider) ctx = engine.rootContext() ctx.setContextProperty('documentModel', QtCore.QStringList()) self.view.setSource(QUrl(SearchResultWidget.qml_location)) self.view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
def changeHTML(self, planlist): u''' 修改HTML,使得其显示景点表的驾车路线 :param planlist: :return: ''' if (len(planlist) > 2): #multipoint driving path str = '"%s"' % planlist[1] if len(planlist) > 3: for i in range(2, len(planlist) - 1): str = str + ',' + '"%s"' % planlist[i] f = open('routePlan.html', 'r+') flist = f.readlines() flist[ 26] = 'driving.search(p1, p2,{waypoints:[%s]});' % str.encode( "utf-8") flist[23] = '' flist[22] = 'var p1 = "%s"\nvar p2 = "%s"\n' % ( planlist[0].encode("utf-8"), planlist[-1].encode("utf-8")) f = open('routePlan_test.html', 'w+') f.writelines(flist) f.close() url_path = 'file:///' + guiPath + '/routePlan_test.html' elif (len(planlist) == 2): # two points driving path f = open('routePlan.html', 'r+') flist = f.readlines() flist[26] = 'driving.search(p1, p2);' flist[23] = '' flist[22] = 'var p1 = "%s"\nvar p2 = "%s"\n' % ( planlist[0].encode("utf-8"), planlist[-1].encode("utf-8")) f = open('routePlan_test.html', 'w+') f.writelines(flist) f.close() url_path = 'file:///' + guiPath + '/routePlan_test.html' else: # one point search(No path) f = open('spot_search.html', 'r+') flist = f.readlines() flist[25] = ' local.search("%s");\n' % planlist[0].encode("utf-8") f = open('spotSearch_test.html', 'w+') f.writelines(flist) f.close() url_path = 'file:///' + guiPath + '/spotSearch_test.html' self.planView.setUrl(QUrl(url_path)) self.planView.show()
def __init__( self, title="Simple Web Browser", urlInit="file:///home/david/Documentos/CreadorDiagramas/miDiagrama.html" ): QMainWindow.__init__(self) self.setWindowTitle(title) self.widget = QWidget(self) # Widget para el navegador self.webview = QWebView() self.webview.load(QUrl(urlInit)) self.webview.urlChanged.connect(self.url_changed) # Ir hacia atrás self.back_button = QPushButton("<") self.back_button.clicked.connect(self.webview.back) # Ir hacia adelante self.forward_button = QPushButton(">") self.forward_button.clicked.connect(self.webview.forward) # Actualizar la página self.refresh_button = QPushButton("Actualizar") self.refresh_button.clicked.connect(self.webview.reload) # Barra de direcciones self.url_text = QLineEdit() # Cargar la página actual self.go_button = QPushButton("Ir") self.go_button.clicked.connect(self.url_set) self.toplayout = QHBoxLayout() self.toplayout.addWidget(self.back_button) self.toplayout.addWidget(self.forward_button) self.toplayout.addWidget(self.refresh_button) self.toplayout.addWidget(self.url_text) self.toplayout.addWidget(self.go_button) self.layout = QVBoxLayout() self.layout.addLayout(self.toplayout) self.layout.addWidget(self.webview) self.widget.setLayout(self.layout) self.setCentralWidget(self.widget) QMetaObject.connectSlotsByName(self)
def _download_qgis(packageUrl, handle): from qgis.core import QgsNetworkAccessManager request = QNetworkRequest(QUrl(packageUrl)) reply = QgsNetworkAccessManager.instance().get(request) evloop = QEventLoop() reply.finished.connect(evloop.quit) evloop.exec_(QEventLoop.ExcludeUserInputEvents) content_type = reply.rawHeader('Content-Type') if bytearray(content_type) == bytearray('text/plain; charset=utf-8'): handle.write(bytearray(reply.readAll())) else: msg = 'Failed to download %s\n\nPlease check your QGIS network settings and authentication db' % (packageUrl) ret_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) if ret_code: msg += '\n\nThe HTTP status code was %d.' % (ret_code) raise Exception(msg)