我最终要完成的是捕获用户输入网站的用户名和密码。例如,如果用户在Facebook的登录名中输入“test@example.com”作为电子邮件地址,则点击提交,我想将该电子邮件地址存储在我的PyQt应用程序中。
我最接近实现此目的的是使用一系列JavaScript命令将侦听器放在“Login Button”上,该“Login Button”返回user参数的当前值。我的问题是PyQt提供的回调是在runJavaScript
函数完成时,而不是javascript事件监听器。我想知道是否有任何方法可以从JavaScript函数中捕获回调函数,或者我是否有更好的方法来执行此操作。
import os
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEngineView
class WebPage(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
#self.page().runJavaScript("document.getElementById("myBtn").addEventListener("click", displayDate)", print)
def _on_load_finished(self):
print("Finished Loading")
cmds = ["btn=document.getElementById('u_0_r')", # Login Button
"user=document.getElementsByName('email')[0]",
"function get_username(){return user.value}",
"btn.addEventListener('click', get_username)"]
self.page().runJavaScript("; ".join(cmds), lambda x: print("test: %s" % x))
if __name__ == "__main__":
app = QApplication(sys.argv)
web = WebPage()
web.show()
sys.exit(app.exec_()) # only need one app, one running event loop
答案 0 :(得分:2)
我找到了一个使用“urlChanged”信号的工作,这个信号似乎对我的应用程序起作用
import os
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QWidget
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInterceptor
class WebPage(QWebEngineView):
def __init__(self):
QWebEngineView.__init__(self)
self.current_url = ''
self.load(QUrl("https://facebook.com"))
self.loadFinished.connect(self._on_load_finished)
self.urlChanged.connect(self._on_url_change)
def _on_load_finished(self):
self.current_url = self.url().toString()
def _on_url_change(self):
self.page().runJavaScript("document.getElementsByName('email')[0].value", self.store_value)
def store_value(self, param):
self.value = param
print("Param: " +str(param))
if __name__ == "__main__":
app = QApplication(sys.argv)
web = WebPage()
web.show()
sys.exit(app.exec_()) # only need one app, one running event loop