我正在尝试获取所有DOM元素的边界框的坐标。我目前正在使用pyqt5,并且可以使用以下代码成功完成:
class Browser(QWebEngineView):
def __init__(self):
super(Browser, self).__init__()
self.loadFinished.connect(self._load_finished)
def _result(self, x):
for tagname, top, right, bottom, left in x:
print "%8s %3d %3d %3d %3d"%(tagname, top, right, bottom, left)
def _load_finished(self):
js_script = """
function get_coordinates() {
var res = [];
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var rect = all[i].getBoundingClientRect()
res.push([all[i].tagName, rect.top, rect.right, rect.bottom, rect.left]);
}
return res;
}
get_coordinates();
"""
self.page().runJavaScript(js_script, self._result)
app = QApplication(sys.argv)
br = Browser()
url = QUrl(url_address)
br.load(url)
br.show()
app.exec_()
这个代码的一个缺点是它打开一个浏览器来显示网页(因为br.show()),我想知道是否有任何方法可以防止这种情况。我简单地评论了br.show()并运行了代码。但是,某些DOM元素的坐标结果与原始元素不同。
感谢,
答案 0 :(得分:1)
如果您不想显示窗口,请使用QWebEnginePage
:
class Browser(QWebEnginePage):
def __init__(self):
super(Browser, self).__init__()
self.loadFinished.connect(self._load_finished)
def _result(self, x):
for tagname, top, right, bottom, left in x:
print("%8s %3d %3d %3d %3d"%(tagname, top, right, bottom, left))
def _load_finished(self):
js_script = """
function get_coordinates() {
var res = [];
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var rect = all[i].getBoundingClientRect()
res.push([all[i].tagName, rect.top, rect.right, rect.bottom, rect.left]);
}
return res;
}
get_coordinates();
"""
self.runJavaScript(js_script, self._result)
app = QApplication(sys.argv)
br = Browser()
url = QUrl(url_address)
br.load(url)
app.exec_()