2013-01-05 24 views
2

我很努力地使用QWebElement。作爲一項練習,我想從第http://www.google.com頁獲取「Google」徽標。該圖像位於<div id="hplogo" ...>,但我不知道如何提取它。我如何在下面的代碼中使用「doc」QWebElement? (「CSS選擇器」對我來說是個晦澀的術語)。 謝謝。使用QWebElement解析HTML,如何提取圖像?

from PyQt4.QtGui import QApplication 
from PyQt4.QtWebKit import QWebView 
from PyQt4.QtCore import QUrl 

app = QApplication([]) 
view = QWebView() 
view.load(QUrl("http://google.com")) 
view.show() 
doc = view.page().currentFrame().documentElement() # run this after 'loadFinished' 

回答

3

獲得 「谷歌」 標誌的網址,這樣做:

elem = doc.findFirst("div#hplogo") 
qstring = elem.attribute('style') 
regexp = QRegExp("^(.*:)?url\((.*)\)") 
if regexp.indexIn(qstring) > -1: 
    imageURL = regexp.capturedTexts()[-1] 

它返回imageURL = "/images/srpr/logo1w.png"。在這種情況下需要使用正則表達式,因爲URL是字符串的一部分。要獲得圖像並將其顯示在標籤上,請執行以下操作:

request = QNetworkRequest(QUrl("http://www.google.com/images/srpr/logo1w.png")) 
reply = view.page().networkAccessManager().get(request) 
byte_array = reply.readAll() 
image = QImage() 
image.loadFromData(byte_array) 
label = QLabel() 
label.setPixmap(QPixmap(image)) 
label.show() 
2

你只需要提取包含圖像的<img/> HTML標籤的src屬性,然後創建一個src屬性的圖像。

imgTags = doc.findAll("img") 
imgRightTag = QWebElement() 

# Find the right <img/> tag and put it in imgRightTag 

imgURL = "http://www.google.com" + imgRightTag.attribute("src") 
image = QImage(imgURL) 
+0

對不起,這是一個廢話,但複製粘貼您的代碼似乎不起作用。我試圖解釋它,並設法從'imgURL = doc.findFirst(「img」)。attribute(「src」)'獲得一個QString,其值等於'/ images/icons/product/chrome-48。 png''。但是我在下一步努力......我如何訪問這個字符串應該指向的圖像? QImage()。load(imgURL)返回False。 – Olivier

+0

預先安裝基本URL。 「http://google.com/images/icons/product/chrome-48.png」應該可以工作。我編輯了我的答案。 –

+0

它似乎沒有與prepended鏈工作(我寧願不再下載一個剛下載的圖像)。 – Olivier