我很难使用QWebElement。作为练习,我想从页面http://www.google.com捕获“谷歌”徽标。图像是<div id="hplogo" ...>格式的,但我不知道如何提取它。在下面的代码中,我应该如何使用"doc“QWebElement?("CSS选择器“对我来说是个晦涩难懂的术语)。谢谢。
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'发布于 2013-01-20 05:22:02
要获取"Google“徽标的URL,请执行以下操作:
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"。在这种情况下有必要使用regexp,因为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()发布于 2013-01-05 23:37:08
您只需提取包含图像的<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)https://stackoverflow.com/questions/14173255
复制相似问题