用Python下载文件的问题

3 投票
4 回答
1107 浏览
提问于 2025-04-15 11:48

我想通过点击网页上的一个链接来自动下载一个文件。点击链接后,我会看到一个“文件下载”窗口,里面有“打开”、“保存”和“取消”这几个按钮。我希望能够自动点击“保存”按钮。

我使用了watsup这个库,代码是这样的:

from watsup.winGuiAuto import *

optDialog = findTopWindow(wantedText="File Download")

SaveButton = findControl(optDialog,wantedClass="Button", wantedText="Save")

clickButton(SaveButton)

但不知道为什么,这个方法不管用。有趣的是,完全一样的代码在点击“取消”按钮时却能正常工作,但在“保存”或“打开”按钮上就不行。

有没有人知道我该怎么做?

非常感谢,
Sasha

4 个回答

0

Sasha,

这个链接中的代码 http://bytes.com/groups/python/23100-windows-dialog-box-removal 应该是可以用的。它使用了ctypes,而不是watsup.winGuiAuto,并且依赖于win32的调用。下面是代码:

from ctypes import *
user32 = windll.user32

EnumWindowsProc = WINFUNCTYPE(c_int, c_int, c_int)

def GetHandles(title, parent=None):
'Returns handles to windows with matching titles'
hwnds = []
def EnumCB(hwnd, lparam, match=title.lower(), hwnds=hwnds):
title = c_buffer(' ' * 256)
user32.GetWindowTextA(hwnd, title, 255)
if title.value.lower() == match:
hwnds.append(hwnd)

if parent is not None:
user32.EnumChildWindows(parent, EnumWindowsProc(EnumCB), 0)
else:
user32.EnumWindows(EnumWindowsProc(EnumCB), 0)
return hwnds

这里有个例子,展示如何调用这个代码来点击任何标题为“Downloads properties”的窗口中的确定按钮(通常这样的窗口可能有0个或1个):

for handle in GetHandles('Downloads properties'):
for childHandle in GetHandles('ok', handle):
user32.SendMessageA(childHandle, 0x00F5, 0, 0) # 0x00F5 = BM_CLICK
1

保存按钮可能并不是一直可以点击的。虽然你看起来觉得它是可用的,但程序可能会看到一个你没注意到的初始状态。你需要检查一下它的状态,等到它可以使用的时候再点击。

[编辑] 不过,也有可能罗伯特说得对,那个对话框出于安全原因会直接不理你。在这种情况下,我建议你使用BeautifulSoup来解析HTML,提取出网址,然后用Python的urllib2模块来下载文件。

1

萨莎,

你提到的那个文件对话框(也就是安全警告文件下载对话框)很可能不会像你想的那样响应窗口消息,这是出于安全考虑。这个对话框是专门设计的,只能通过用户用鼠标点击“确定”按钮来响应。我想你会发现“运行”按钮也不能这样使用。

撰写回答