如何使用QWebElement设置输入(type=&文件&)的值? [英] How to set value of input(type="file") with QWebElement?

查看:23
本文介绍了如何使用QWebElement设置输入(type=&文件&)的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用QtWebKit模块将照片上载到vk.com。我面临的问题是无法正确填充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()
需要注意的是,由于浏览器安全策略的原因,不可能从Java脚本中填充文件输入值。但是,应该可以使用Qt API,更具体地说,是QWebElement::setAttribute()方法。这就是我所做的,…没有效果(好的,photoInput.attribute('value')返回预期结果,但photoInput.evaluateJavaScript('return this.value;').toString()返回空字符串,输入的onchange处理程序也不被触发)。

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

任何帮助都是非常好的。
谢谢。

推荐答案

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

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

这似乎起作用了:

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_())

这篇关于如何使用QWebElement设置输入(type=&文件&)的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆