2016-07-19 78 views
0

我正在嘗試在google上進行搜索,然後加載第一個鏈接。如何關注PyQT4的鏈接?

我修改了一些示例代碼,我在網上找到:

class Render(QWebPage): 
    def __init__(self, url): 
    self.app = QApplication(sys.argv) 
    QWebPage.__init__(self) 
    self.loadFinished.connect(self._loadFinished) 
    self.mainFrame().load(QUrl(url)) 
    self.app.exec_() 

    def _loadFinished(self, result): 
    self.frame = self.mainFrame() 
    self.app.quit() 

url = 'https://www.google.com' 
r = Render(url) 
el = r.mainFrame().findFirstElement('input[name=q]') 
el.setAttribute('value', 'stackoverflow') 
button = r.mainFrame().findFirstElement('input[name=btnK]') 

# Now click on the Search button 
button.evaluateJavaScript('this.click()') 

# Print out what we see 
print r.frame.toHtml().toAscii() 

這應該是點擊我的術語「計算器」的搜索按鈕。但是當我加載打印的html時,我只能看到搜索欄包含我的文本,就好像搜索按鈕還沒有被點擊一樣。

如何點擊搜索按鈕,找到第一個結果,然後打印出html源代碼?

回答

0

所以,我想直接在我的腦海中......您正在加載默認的谷歌網頁,將搜索文本框設置爲您的搜索詞,然後嘗試模仿「搜索?」的點擊。

直接訪問谷歌的搜索會不會容易得多?即:

http://www.google.com/search?q=stackoverflow 

是否有某些原因需要通過網頁間接完成?

0

經過與代碼的一點點撥,我發現button.isNull()返回True。它基本上意味着沒有稱爲input[name=btnK]的元素。所以你可能想要搜索正確的元素。

但是,啓動一個實例是Qt類中的QApplication是有問題的,不推薦使用。它會導致未知/未知的崩潰。這裏是你如何修改你的代碼。

class Render(QWebPage): 
    def __init__(self, url): 

     # Init 
     super(QWebPage, Render).__init__(self) 

     # Initial Signal-Slot connection 
     self.loadFinished.connect(self.urlLoadFinished) 

     # If you want to know what's happening 
     sys.stdout.write("Loading %s... " % url) 
     sys.stdout.flush() 

     # Start the load procedure 
     self.mainFrame().load(QUrl(url)) 

    def urlLoadFinished(self, result): 

     # Loading complete 
     print("[DONE]") 

     # You do not want a loop back here once the button is clicked 
     self.loadFinished.disconnect(self.urlLoadFinished) 

     # Get your input element 
     el = self.mainFrame().findFirstElement('input[name=q]') 

     # Fill it with the quesry you want 
     el.setAttribute('value', 'stackoverflow') 

     # Get you Button 
     button = self.mainFrame().findFirstElement('input[name=btnK]') 

     if not button.isNull() : 
      # Connect the loadFinished signal to the final evaluation slot 
      self.loadFinished.connect(self.printEvaluatedOutput) 

      # Now click on the Search button 
      print button.evaluateJavaScript('this.click()') 

     else: 
      print "Button not found" 
      qApp.quit() 

    def printEvaluatedOutput(self) : 

     # Print the contents of the 
     print self.mainFrame().toHtml().toAscii() 

     qApp.quit() 

if __name__ == '__main__' : 

    app = QApplication(sys.argv) 

    renderer = Render('https://www.google.com') 

    sys.exit(app.exec_()) 

EDIT1: 再過了些閒逛,我發現了,因爲我們看到在檢查按鈕谷歌的搜索按鈕被一個名爲btnG而非btnK註冊。用input[name=btnG]代替input[name=btnk]就可以做到你想要的。