I'm trying to create a dedicated web browser for my work with some buttons which can automate tasks for me. The script I found is like below, but I'm struggling with the piece that would enter text in de search field and then hit the button. (This is a test piece ofcourse)
Does anyone know how to automate this, using the pyqt5 example found?
Something like:
self.browser.getObjectbyName("ObjName").setText("newtext")
I've been googling for hours but have not found any example code yet.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow,self).__init__(*args, **kwargs)
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://www.google.com"))
self.setCentralWidget(self.browser)
self.show()
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
There are several tools in QtWebEngine to perform automated tasks on web pages:
Execute js script using runJavaScript() method.
Use QtWebChannel to exchange information and perform tasks between python and the web page.
Implement userscripts through QWebEngineScript.
In this case I will show a demo of how to do an automated search using the first option:
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEngineView
import sys
script = """
var input = document.querySelector("body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form > div:nth-child(1) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input")
input.value = "StackOverflow"
var form = document.querySelector("body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form")
form.submit()
"""
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.browser = QWebEngineView()
self.browser.loadFinished.connect(self.handle_load_finished)
self.browser.setUrl(QUrl("http://www.google.com"))
self.setCentralWidget(self.browser)
def handle_load_finished(self, ok):
if ok:
if self.browser.url() == QUrl("https://www.google.com/"):
self.browser.page().runJavaScript(script)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
Related
when a JavaScript program requests to open a document in a new window, QWebEnginePage::createWindow() would be called to create a new window, while I want to (1) open the new window using QDesktopServices.openUrl(url) instead, and (2) keep the view in my QWebEngineView unchanged. My solution cannot satisfy (2), so any simpler solutions ?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWebEngineCore import *
import sys,os
class WebEnginePage(QWebEnginePage):
def __init__(self, parent, mdicts=[]):
super().__init__(parent)
self.backwardUrl=''
def acceptNavigationRequest(self, url, navigationType, isMainFrame): # Navigation requests can be delegated to the Qt application instead of having the HTML handler engine process them by overloading this function. This is necessary when an HTML document is used as part of the user interface, and not to display external data, for example, when displaying a list of results.# The QWebEngineUrlRequestInterceptor class offers further options for intercepting and manipulating requests.
# print('acceptNavigationRequest-----------------', navigationType, isMainFrame)
if self.backwardUrl and isMainFrame:
print('blocked------------',self.backwardUrl)
self.setUrl(self.backwardUrl)
QDesktopServices.openUrl(self.backwardUrl)
self.backwardUrl=''
return False
return True
def createWindow(self, windowType):
print('createWindow')
self.backwardUrl=self.url()
return self
class WebEngineView(QWebEngineView):
def __init__(self, parent=None):
super().__init__(parent)
# self.mousePressEvent=lambda event:print('mousePressEvent',event.pos())
# self.mouseMoveEvent=lambda event:print('mouseMoveEvent',event.pos())
self.webPage = WebEnginePage(self)#self.page() # QWebEnginePage()
self.setPage(self.webPage)
# self.setUrl(QUrl('https://dict.eudic.net/liju/en/good#TingLiju'))
self.webPage.setUrl(QUrl('https://dict.eudic.net/liju/en/good#TingLiju'))
if __name__ == "__main__":
app = QApplication(sys.argv)
webEngineView = WebEngineView()
webEngineView.show()
sys.exit(app.exec_())
A possible solution is to create a page that only serves to obtain the url, and when you get it, delete it and launch the url with QDesktopServices::openUrl():
class FakePage(QWebEnginePage):
def __init__(self, parent=None):
super().__init__(parent)
self.urlChanged.connect(self.handle_url_changed)
#pyqtSlot(QUrl)
def handle_url_changed(self, url):
QDesktopServices.openUrl(url)
self.deleteLater()
class WebEnginePage(QWebEnginePage):
def createWindow(self, windowType):
return FakePage(self)
class WebEngineView(QWebEngineView):
def __init__(self, parent=None):
super().__init__(parent)
self.webPage = WebEnginePage(self)
self.setPage(self.webPage)
self.webPage.setUrl(QUrl("https://dict.eudic.net/liju/en/good#TingLiju"))
So I'm building a simple Web Browser using PyQt5, with QtWebEngineView, it works fine, but when I type something in the address bar and hit enter, the current page changes but the entered web address does not load, the screen remains blank.
It doesn't work with https:// either
"""A Simple Web Browser Written in Python and PyQt5"""
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QIcon
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolBar, QAction, QLineEdit
class PyChromeWindow(QMainWindow):
DEFAULT_SEARCH_ENGINE = QUrl("https://www.google.com")
def __init__(self):
super(PyChromeWindow, self).__init__()
self.browser = QWebEngineView(self)
self.browser.setUrl(self.DEFAULT_SEARCH_ENGINE)
# ToolBar
self.browser_tool_bar = QToolBar()
self.addToolBar(self.browser_tool_bar)
# Back Action
self.back_btn = QAction(QIcon('./resources/back_arrow16px.png'), 'Back')
self.back_btn.triggered.connect(self.browser.back)
self.browser_tool_bar.addAction(self.back_btn)
# Forward Action
self.forward_action = QAction(QIcon('./resources/forward_arrow16px.png'), 'Forward')
self.forward_action.triggered.connect(self.browser.forward)
self.browser_tool_bar.addAction(self.forward_action)
# Refresh Action
self.refresh_action = QAction(QIcon('./resources/refresh_icon16px.png'), 'Refresh')
self.refresh_action.triggered.connect(self.browser.reload)
self.browser_tool_bar.addAction(self.refresh_action)
# Home Action
self.home_action = QAction(QIcon('./resources/home_icon16px.png'), 'Home')
self.home_action.triggered.connect(lambda: self.browser.setUrl(self.DEFAULT_SEARCH_ENGINE))
self.browser_tool_bar.addAction(self.home_action)
# Address Bar
self.address_bar = QLineEdit()
self.address_bar.returnPressed.connect(self.navigate_to_url)
self.browser_tool_bar.addWidget(self.address_bar)
self.setCentralWidget(self.browser)
self.showMaximized()
def navigate_to_url(self):
"""Navigate to a specific URL"""
url = QUrl(self.address_bar.text())
self.browser.load(url)
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setApplicationName("PyChrome")
window = PyChromeWindow()
app.exec_()
"www.google.com" is not a valid url for QWebEngineView, in this case you must use QUrl::fromUserInput() which deduces a valid url.
url = QUrl.fromUserInput(self.address_bar.text())
I have made a web browser using pyqt5 and PyQtWebEngine.It works fine but when I click on a hyperlink with target="_blank" then it does not work but how will I fix it. You can view its source code by clicking on this link https://github.com/SaptakBhoumik/WebPlus
. Please review my code and tell me what to do
As noted in the docs:
_blank: usually a new tab, but users can configure browsers to open a new window instead.
That is, the objective is not to reload the page but to create a new tab, and then to obtain that request you must override the createWindow method of QWebEngineView (or QWebEnginePage):
from functools import cached_property
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
class WebView(QtWebEngineWidgets.QWebEngineView):
def createWindow(self, type_):
if not isinstance(self.window(), Browser):
return
if type_ == QtWebEngineWidgets.QWebEnginePage.WebBrowserTab:
return self.window().tab_widget.create_tab()
class TabWidget(QtWidgets.QTabWidget):
def create_tab(self):
view = WebView()
index = self.addTab(view, "(Untitled)")
self.setTabIcon(index, view.icon())
view.titleChanged.connect(
lambda title, view=view: self.update_title(view, title)
)
view.iconChanged.connect(lambda icon, view=view: self.update_icon(view, icon))
self.setCurrentWidget(view)
return view
def update_title(self, view, title):
index = self.indexOf(view)
self.setTabText(index, title)
def update_icon(self, view, icon):
index = self.indexOf(view)
self.setTabIcon(index, icon)
class Browser(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setCentralWidget(self.tab_widget)
view = self.tab_widget.create_tab()
view.load(
QtCore.QUrl(
"https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_a_target"
)
)
#cached_property
def tab_widget(self):
return TabWidget()
def main():
app = QtWidgets.QApplication(sys.argv)
w = Browser()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Note: I recommend that you review the official example: WebEngine Widgets Simple Browser Example, in addition to its implementation in PySide2 which is easily translatable to PyQt5 where this feature and many more are implemented.
I have a very simple application that is intended to run a web browser in PyQt window.
The code runs without errors the window opens and then 'blinks' briefly and then is blank.
I am running MacOS(10.13.6) Python 3.8 and PyQt5 5.14 and PyQtWebEngine 5.14.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow,self).__init__(*args, **kwargs)
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://google.com"))
self.setCentralWidget(self.browser)
self.show()
app = QApplication(sys.argv)
window = MainWindow()
app.exec_()
I am making a web browser using PyQt5. I am using the following code:
import PyQt5
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWebKitWidgets import QWebView , QWebPage
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtNetwork import *
import sys
from optparse import OptionParser
class Browser(QWebView):
def __init__(self):
# QWebView
self.view = QWebView.__init__(self)
#self.view.setPage(MyBrowser())
self.setWindowTitle('Loading...')
self.titleChanged.connect(self.adjustTitle)
#super(Browser).connect(self.ui.webView,QtCore.SIGNAL("titleChanged (const QString&)"), self.adjustTitle)
def load(self,url):
self.setUrl(QUrl(url))
def adjustTitle(self):
self.setWindowTitle(self.title())
app = QApplication(sys.argv)
view = Browser()
view.showMaximized()
view.load("https://duckduckgo.com")
app.exec_()
However, this is what I get:
Can someone please tell me where I am going wrong? Note that it is not a problem of the website. I have tried it with Wikipedia, Stack Overflow and Google. I am using PyQt5 version 5.10.1.
In case you want fullscreen, you have to use:
class Browser(QWebView):
def __init__(self):
# QWebView
self.view = QWebView.__init__(self)
#self.view.setPage(MyBrowser())
self.setWindowTitle('Loading...')
self.titleChanged.connect(self.adjustTitle)
self.showFullScreen()
class Browser(QWebView):
def __init__(self):
super().__init__()
def load(self, url):
self.setUrl(QUrl(url))
def adjustTitle(self):
self.setWindowTitle(self.title())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Browser()
window.setWindowTitle('Loading...')
window.titleChanged.connect(window.adjustTitle)
window.load("https://duckduckgo.com")
window.showMaximized()
sys.exit(app.exec_())
The program does not know the real sizes of your device so it creates a maximum on its assumed geometry.
You should provide the actual geometry by resize then call showMaximized. So that your geometry will be reachable by the program and a true maximized window will be displayed.
self.resize(998, 878)
self.showMaximized()