Python 获取QtWebKit、PyQt4和autoscroll的QWebView中某个元素的坐标,以确定其位置
下面是一个简单的代码,可以在Python 获取QtWebKit、PyQt4和autoscroll的QWebView中某个元素的坐标,以确定其位置,python,pyqt4,qtwebkit,qwebview,Python,Pyqt4,Qtwebkit,Qwebview,下面是一个简单的代码,可以在QWebView中打开一个站点(比如yahoo.com)。加载完站点后,它会滚动到某个位置(例如,QPoint(100300))。我们需要等待站点完成加载,否则它不会自动滚动,因此loadFinishedsignal 但问题是:我怎样才能找到一个元素的坐标(比如yahoo.com上的“All Stories”)并自动滚动到它的位置,就像我在下图中手动操作一样?在QWebFrame中有类似findFirstElement,findAllElements的函数,但我不知道
QWebView
中打开一个站点(比如yahoo.com)。加载完站点后,它会滚动到某个位置(例如,QPoint(100300)
)。我们需要等待站点完成加载,否则它不会自动滚动,因此loadFinished
signal
但问题是:我怎样才能找到一个元素的坐标(比如yahoo.com上的“All Stories”)并自动滚动到它的位置,就像我在下图中手动操作一样?在QWebFrame
中有类似findFirstElement
,findAllElements
的函数,但我不知道如何使用它们来查找x,y坐标
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
def loadFinished():
web.page().mainFrame().setScrollPosition(QPoint(100, 300))
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://yahoo.com"))
web.connect(web, SIGNAL('loadFinished(bool)'), loadFinished)
web.setGeometry(700, 500, 300, 500)
web.setWindowTitle('yahoo')
web.show()
sys.exit(app.exec_())
使用:
对于任何感兴趣的人,这里是我的最后一段代码(基于ekhumoro建议使用
QWebElement.geometry()
):
def loadFinished():
elements = web.page().mainFrame().findAllElements(css_selector)
for index in range(elements.count()):
print(elements.at(index).geometry())
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
def loadFinished():
html = web.page().mainFrame().documentElement()
# I couldn't find a way to find html element by text 'All Stories',
# so copied this weird unique attribute from yahoo page source code
el = html.findFirst('a[data-ylk="sec:strm;cpos:1;elm:itm;elmt:fltr;pos:0;ft:1;itc:1;t1:a3;t2:strm;t3:lst"]')
qp = el.geometry().topLeft() # returns QPoint object
# we can either use QPoint position as is:
# web.page().mainFrame().setScrollPosition(qp)
# or calibrate x, y coordinates a little:
web.page().mainFrame().setScrollPosition(QPoint(qp.x() - 15, qp.y()))
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://yahoo.com"))
web.loadFinished.connect(loadFinished)
web.setGeometry(700, 500, 300, 500)
web.setWindowTitle('yahoo')
web.show()
sys.exit(app.exec_())