我想使用Python QWebView在Google上逐个搜索关键字。我的代码如下,其中只有最后一次关键字搜索并返回该关键字结果。
如果有任何想法如何使用Python Qt在Google上搜索多个关键字,请分享您的代码。
#!/usr/bin/env python
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4 import QtCore
import time
from PyQt4.QtWebKit import QWebView, QWebElement, QWebElementCollection
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
layout = QFormLayout()
self.setLayout(layout)
self.web = QWebView()
layout.addRow("Search",self.web)
self.start = QPushButton("Start")
self.start.setDefault(True)
self.start.clicked.connect(lambda:self.search_keyword(self.start))
layout.addRow(self.start)
def search_keyword(self,b):
for keyword in ["Python Tutorial","Android Tutorial","VB Tutorial"]:
self.web.load(QUrl("http://www.google.com?q="+keyword))
self.web.show()
print self.web.connect(self.web, QtCore.SIGNAL('loadFinished(bool)'), self._loadFinished)
def _loadFinished(self,ok):
frame = self.web.page().mainFrame()
doc=frame.documentElement()
button = doc.findFirst("input[type=submit]")
button.evaluateJavaScript("this.click()")
self.web.loadFinished.connect(self.searchResults)
def searchResults(self):
results = self.web.page().currentFrame().documentElement().findAll('h3.r a').toList()
for result in results:
url=str(result.attribute('href'))
link=url[url.index('q')+2:url.index('&')]
print link
break
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
ex.setGeometry(300, 200, 470, 320)
sys.exit(app.exec_())
if __name__ == '__main__':
main()