【问题标题】:Qt, how to simulate user clicks in input type=fileQt,如何在输入类型=文件中模拟用户点击
【发布时间】:2014-03-16 19:04:02
【问题描述】:

简而言之,我的问题是:我想自动将图片上传到网站。但是,我无法模拟输入 type=file。

我在网页中有以下输入元素。

<input id="fileupload" type="file" name="files[]" data-url="/server/images/e1b2d17b7b7eccef21a0a0ba1756d35c/upload/" multiple="">

我知道出于安全原因,使用 JS 或 JQuery 模拟此元素已被禁用。没关系。但是,我将页面加载到我的 QWebElement 中,并且我想通过模拟必要的鼠标点击来自动上传图像。我设法点击了上传按钮,但我无法模拟在打开的对话框中输入任何文件夹名称或文件名。我想我需要专注于对话框,但做不到。谁能指导我一下?

【问题讨论】:

  • 也许你可以看看 selenium 是如何做到的,虽然它是 python,但仍然如此。

标签: jquery qt webkit qtwebkit qwebview


【解决方案1】:

您应该发送鼠标点击事件来输入点坐标。这是执行此操作的 PyQt 代码。

# We need to scroll our window, to make input "visible" and get it's coordinates
el_pos = el.geometry().center()  # el - QWebElement points to input
self._page.mainFrame().setScrollPosition(el_pos)  # self._page - QWebPage
scr_pos = self._page.mainFrame().scrollPosition()
point_to_click = el_pos - scr_pos

# Create click on coordinates
press = QMouseEvent(QMouseEvent.MouseButtonPress, point_to_click, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
release = QMouseEvent(QMouseEvent.MouseButtonRelease, point_to_click, Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
QApplication.postEvent(self._handler, press)  # self._handler - QWebView
QApplication.postEvent(self._handler, release)

选择文件对话框“打开”后,Qt 调用QWebPage.chooseFile() 函数来获取文件名,应该选择该文件名。我们需要在 out QWebPage 中重新实现这个方法:

class WebPage(QWebPage):
    def __init__(self):
        QWebPage.__init__(self)
        self.file_name = 'test.png'  # file name we want to be choosed

    def chooseFile(self, frame, suggested_file):
        return self.file_name  # file will be choosen after click on input type=file

更新:

还有一件事。如果输入允许选择多个文件,重新实现 QWebPage.chooseFile() 将不起作用。要处理这个问题,您应该添加对QWebPage::ChooseMultipleFilesExtension 的支持。这里是simple example 怎么做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2023-04-04
    • 2018-02-23
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多