【问题标题】:Qt: Take over system open file dialogQt:接管系统打开文件对话框
【发布时间】:2012-10-26 23:01:24
【问题描述】:

我想使用 PyQt4 的 QWebView 自动将文件上传到网站,但有一部分我还不知道。要上传文件,该网站有一个按钮,它会打开一个对话框,您应该从中选择本地文件。所以,这些是我的问题:) 有没有办法在我单击按钮后控制该对话框?有没有更好的方法来实现这一点?

编辑

网站是https://maps.google.com/,我正在通过我的地点>创建地图>导入上传一个.kml文件。

【问题讨论】:

  • 能否提供网址?
  • @enginefree 当然,会编辑帖子
  • 我提供的答案有用吗?
  • @enginefree 还不能检查,但看起来不错,我可能会在时间限制到期之前裁定你的赏金,谢谢!

标签: python qt pyqt4 qwebview qfiledialog


【解决方案1】:

这是一个纯粹的 PyQt4 演示,或多或少地再现了默认实现:

import sys
from PyQt4 import QtCore, QtGui, QtWebKit

class WebPage(QtWebKit.QWebPage):
    def chooseFile(self, frame=None, path=''):
        return QtGui.QFileDialog.getOpenFileName(self.parent(), '', path)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    view = QtWebKit.QWebView()
    view.setPage(WebPage(view))
    view.load(QtCore.QUrl('https://maps.google.com/'))
    view.show()
    sys.exit(app.exec_())

【讨论】:

    【解决方案2】:

    您正在寻找的可能是QWebPage::chooseFile()(我想这也取决于网站如何处理它)。重新实现它,看看它是否足够。做任何你想做的事情并返回选择的文件路径。

    编辑:现在您提供了我测试过的链接并且似乎可以工作。

    【讨论】:

      【解决方案3】:

      好的,首先让我从背景信息和参考资料开始。

      我将使用的模块是pywin32 下载here,特别是win32gui,API 参考here

      现在,在您可以操作对话框之前,您必须“导航”到窗口句柄,以下使用 win32.FindWindow API 参考 here,看起来像这样,其中两个输入是 lpclassName 在这种情况下#32770(代表对话)引用 herelpWindowName,在这种情况下是 File Upload

      HWND WINAPI FindWindow(
        _In_opt_  LPCTSTR lpClassName,
        _In_opt_  LPCTSTR lpWindowName
      ); 
      

      定位文件句柄的代码:

      import win32gui
      
      control = win32gui.FindWindow("#32770", "File Upload")
      

      它存储句柄,在我的例子中是721470

      下一步是在对话框中定位 GUI 对象的句柄,我将展示一个 Cancel 按钮的示例。为了找到句柄,我将在这里使用FindWindowEx API 参考,

      import win32con
      import win32api
      
      ButtonHandle = win32gui.FindWindowEx(control, 0, "Button", "Cancel");
      win32api.SendMessage(ButtonHandle, win32con.BM_CLICK, 0, 0)
      

      BM_CLICK 参考 hereSendMessage 参考 here

      最终代码:

      import win32gui
      import win32api
      import win32con
      
      window = win32gui.GetForegroundWindow()
      title = win32gui.GetWindowText(window)
      control = win32gui.FindWindow("#32770", "File Upload")
      ButtonHandle = win32gui.FindWindowEx(control, 0, "Button", "Cancel")
      win32api.SendMessage(ButtonHandle, win32con.BM_CLICK, 0, 0)
      

      另一种方法是使用watsup.winGuiAuto模块,here,示例如下:

      from watsup.winGuiAuto import *
      
      optDialog = findTopWindow(wantedText="File Upload")
      
      CancelButton = findControl(optDialog,wantedClass="Button", wantedText="Cancel")
      
      clickButton(SaveButton)
      

      但我相信最简单的方法是使用autoithere,我之前在pyqt中使用过它,用于射出命令。

      希望这会有所帮助!

      其他参考资料(pywin32 版本):

      win32guihere

      win32apihere

      【讨论】:

        猜你喜欢
        • 2010-11-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2012-04-25
        • 2010-12-11
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        相关资源
        最近更新 更多