下面的代码工作正常,除了一件事,它不遵循注册链接。 但是,如果我转到我的实际浏览器并在控制台类型中:
document.getElementById("link-signup").click()
它会将我重定向到所需的页面。我认为问题得到了解决,因为我没有在设置中启用某些功能。但我不确定。
感谢您的帮助
#! /usr/bin/env python2.7
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import sys
class GrabberSettings(QWebPage):
def __init__(self):
QWebPage.__init__(self)
self.settings().setAttribute(QWebSettings.AutoLoadImages, False)
class Grabber(QWebView):
def __init__(self):
QWebView.__init__(self)
self.setPage(GrabberSettings())
self.loadFinished.connect(self._loadComplete)
self.doc = self.page().mainFrame().documentElement()
def _loadComplete(self):
print "Done"
link = self.doc.findFirst('a[link-signup]')
if link:
print "link found"
link.evaluateJavaScript('click()')
if __name__ == "__main__":
app = QApplication(sys.argv)
view = Grabber()
gmail = QUrl('https://accounts.google.com')
view.load(gmail)
view.show()
app.exec_()
答案 0 :(得分:4)
我认为click()
失败可能与谷歌网页在加载后使用javascript如何转换原始A
元素有关。如果您将evaluateJavaScript()
来电包裹在alert()
中,则可以看到click
方法为null
link.evaluateJavaScript('this.click')
在链接上调用“click”并不是100%的跨浏览器支持。它需要是一个按钮。
你有几个选择...
(#1)只需导航到链接的
def _loadComplete(self):
page = self.page()
doc = page.currentFrame().documentElement()
link = doc.findFirst('#link-signup')
if link and not link.isNull():
self.load(QUrl.fromEncoded(link.attribute('href').toAscii()))
(#2)模拟网页视图上的点击
def _loadComplete(self):
page = self.page()
doc = page.currentFrame().documentElement()
link = doc.findFirst('#link-signup')
if link and not link.isNull():
pos = link.geometry().center()
self._doMouseClick(page, pos)
else:
print "Link not found"
@staticmethod
def _doMouseClick(obj, pos):
# mouse down
evt = QMouseEvent(QEvent.MouseButtonPress, pos,
Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
QApplication.sendEvent(obj, evt)
# mouse up
evt = QMouseEvent(QEvent.MouseButtonRelease, pos,
Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
QApplication.sendEvent(obj, evt)
(#3)通过javascript
点击链接def _loadComplete(self):
page = self.page()
doc = page.currentFrame().documentElement()
link = doc.findFirst('#link-signup')
if link and not link.isNull():
link.evaluateJavaScript("""
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
this.dispatchEvent(e);
""")