如何使用QWebElement设置input(type =“file”)的值?

时间:2013-03-06 18:36:38

标签: qt qt4 qtwebkit qwebelement

我尝试使用vk.com模块将照片上传到QtWebKit。我面临的问题是无法正确填写input(type="file")的价值。这是我使用的一些相关代码:

def upload():
    print 'uploading...'
    photoInput = web.page().mainFrame().documentElement().findFirst('input[id="photos_upload_input"]')
    assert photoInput, 'No input found'
    photoInput.setAttribute('value', '/Users/elmigranto/Downloads/stuff.png')

    print photoInput.evaluateJavaScript('return this.value;').toString()

值得注意的是,由于浏览器安全策略,Javascript无法填写文件输入值。但是,应该可以使用Qt API,更具体地说,使用QWebElement :: setAttribute()方法。这就是我所做的......没有效果(好吧,photoInput.attribute('value')会返回预期结果,但photoInput.evaluateJavaScript('return this.value;').toString()会返回空字符串,输入' s onchange处理程序也不会被触发)。

设置其他属性没有问题,例如,QWebElement :: addClass()就像魅力一样。

任何帮助都会非常棒。
谢谢。

1 个答案:

答案 0 :(得分:6)

出于安全原因,setAttribute方法可能仍然不起作用。

但是你可以重新定义通常应该打开上传对话框的函数QWebPage::chooseFile并返回文件名以便它在不打开对话框的情况下返回静态文件名,并通过模拟" return&来激活上传。 #34;按下输入元素。

这似乎有效:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import sys

class WebPage(QWebPage):
    def __init__(self, parent = None):
        super(WebPage, self).__init__(parent)
        self.overrideUpload = None

    def chooseFile(self, originatingFrame, oldFile):
        if self.overrideUpload is None:
            return super(WebPage, self).chooseFile(originatingFrame, oldFile)
        result = self.overrideUpload
        self.overrideUpload = None
        return result

    def setUploadFile(self, selector, filename):
        button = self.mainFrame().documentElement().findFirst(selector)
        self.overrideUpload = filename
        # set the focus on the input element
        button.setFocus();
        # and simulate a keypress event to make it call our chooseFile method 
        webview.event(QKeyEvent(QEvent.KeyPress, Qt.Key_Enter, Qt.NoModifier))

def upload():
    print 'uploading...'    
    page.setUploadFile('input[id="photos_upload_input"]',
        '/Users/elmigranto/Downloads/stuff.png') 
    # The change seems to be asynchronous, at it isn't visible 
    # just after the previous call

app = QApplication(sys.argv)
webview = QWebView()
page = WebPage(webview)
webview.setPage(page)
source = '''
<form action="#">
  Select a file: <input type="file" id="photos_upload_input">
  <input type="submit">
</form>
'''
webview.loadFinished.connect(upload)
webview.show()
webview.setHtml(source)
sys.exit(app.exec_())