使用IE从python下载文件

使用IE从python下载文件

本文介绍了使用IE从python下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过IE使用Python下载文件:

I'm trying to download file with Python using IE:

from win32com.client import DispatchWithEvents

class EventHandler(object):
    def OnDownloadBegin(self):
        pass

ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)

ie.Visible = 0

ie.Navigate('http://website/file.xml')

在此之后,我得到一个窗口,询问用户文件的保存位置。如何从python自动保存此文件?

After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?

我需要使用某些浏览器,而不是urllib或机械化,因为在下载之前我需要与一些Ajax功能进行交互的文件

I need to use some browser, not urllib or mechanize, because before downloading file I need to interact with some ajax functionality.

推荐答案

这对我有用,只要IE对话框是在前台,下载的文件在另存为目录中尚不存在:

This works for me as long as the IE dialogs are in the foreground and the downloaded file does not already exist in the "Save As" directory:

import time
import threading
import win32ui, win32gui, win32com, pythoncom, win32con
from win32com.client import Dispatch

class IeThread(threading.Thread):
    def run(self):
        pythoncom.CoInitialize()
        ie = Dispatch("InternetExplorer.Application")
        ie.Visible = 0
        ie.Navigate('http://website/file.xml')

def PushButton(handle, label):
    if win32gui.GetWindowText(handle) == label:
        win32gui.SendMessage(handle, win32con.BM_CLICK, None, None)
        return True

IeThread().start()
time.sleep(3)  # wait until IE is started
wnd = win32ui.GetForegroundWindow()
if wnd.GetWindowText() == "File Download - Security Warning":
    win32gui.EnumChildWindows(wnd.GetSafeHwnd(), PushButton, "&Save");
    time.sleep(1)
    wnd = win32ui.GetForegroundWindow()
if wnd.GetWindowText() == "Save As":
    win32gui.EnumChildWindows(wnd.GetSafeHwnd(), PushButton, "&Save");

这篇关于使用IE从python下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 15:13