我想从网页下载文件。该网页只有一个.zip文件(这是我要下载的文件),但是当我单击.zip文件时,它开始下载,但URL不变(URL仍然保持http://ldn2800:8080/id=2800形式)。考虑到没有http://example.com/1.zip形式的url,如何使用python下载?

另外,当我直接进入页面http://ldn2800:8080/id=2800时,它只打开带有.zip文件的页面,但没有单击就不会下载它。如何使用python下载它?

更新:现在我正在这样做:

if (str(dict.get('id')) == winID):
            #or str(dict.get('id')) == linuxID):
            #if str(dict.get('number')) == buildNo:
            buildTypeId = dict.get('id')
            ID = dict.get('id')
            downloadURL = "http://example:8080/viewType.html?buildId=26009&tab=artifacts&buildTypeId=" + ID
            directory = BindingsDest + "\\" + buildNo
            if not os.path.exists(directory):
                os.makedirs(directory)

            fileName = None
            if buildTypeId == linuxID:
                fileName = linuxLib + "-" + buildNo + ".zip"
            elif buildTypeId == winID:
                fileName = winLib + "-" + buildNo + ".zip"

            if fileName is not None:
                print(dict)
                downloadFile(downloadURL, directory, fileName)

def downloadFile(downloadURL, directory, fileName, user=user, password=password):
    if user is not None and password is not None:
        request = requests.get(downloadURL, stream=True, auth=(user, password))
    else:
        request = requests.get(downloadURL, stream=True)

    with open(directory + "\\" + fileName, 'wb') as handle:
        for block in request.iter_content(1024):
            if not block:
                break
            handle.write(block)


但是,它只是在所需的位置创建了一个zip,但该zip无法打开且没有任何内容。
可以这样做吗?例如在网页上搜索文件名,然后下载匹配的模式?

最佳答案

检查HTTP状态代码以确保没有错误发生。您可以使用内置方法raise_for_status进行此操作:https://requests.readthedocs.io/en/master/api/#requests.Response.raise_for_status

def downloadFile(downloadURL, directory, fileName, user=user, password=password):
    if user is not None and password is not None:
        request = requests.get(downloadURL, stream=True, auth=(user, password))
    else:
        request = requests.get(downloadURL, stream=True)

    request.raise_for_status()

    with open(directory + "\\" + fileName, 'wb') as handle:
        for block in request.iter_content(1024):
            if not block:
                break
            handle.write(block)


您确定没有诸如proxy / fw / etc之类的网络问题吗?

编辑:根据您的上述评论,我不确定这是否能回答您的实际问题。修改后的答案:

您访问的网页包含一个zip文件的链接。您说此链接与页面本身相同。但是,如果您在浏览器中单击它,它将下载文件,而不是再次访问HTML页面。这很奇怪,但是可以用多种方式来解释。请复制/粘贴整个HTML页面代码(包括zip文件的链接),这可能有助于我们理解问题。

10-07 19:37
查看更多