下载zipfile时如何绕过警报窗口?

2024-05-14 21:05:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我打开链接:https://dibbs2.bsm.dla.mil/Downloads/RFQ/Archive/ca210731.zip

这个链接显示窗口,我需要按OK按钮,它会下载文件

警报不是来自浏览器,而是来自页面本身

但当我尝试脚本时:

from io import BytesIO
from zipfile import ZipFile
import requests


def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zipfile.extractall("")

file_link ='https://dibbs2.bsm.dla.mil/Downloads/RFQ/Archive/ca210731.zip'

get_zip(file_link)

这将抛出错误:

zipfile.BadZipFile: File is not a zip file

当我尝试时:

import requests

url = r'https://dibbs2.bsm.dla.mil/Downloads/RFQ/Archive/ca210731.zip'
output = r'downloadedfile.zip'

r = requests.get(url)
with open(output, 'wb') as f:
    f.write(r.content)

这将下载显示OK按钮的页面内容。 如果知道如何解决这个问题,链接将下载zip文件


Tags: httpsimporturlget链接downloadsziprequests
1条回答
网友
1楼 · 发布于 2024-05-14 21:05:37

我相信您正在使用selenium接受答案,以下是使用selenium可以做的事情:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

profile = webdriver.FirefoxProfile()

profile.set_preference("browser.download.folderList",1)
# 0 for desktop
# 1 for default download folder
# 2 for specific folder 
# You can specify directory by using profile.set_preference("browser.download.dir","<>")

profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream")
profile.set_preference("browser.helperApps.alwaysAsk.force", False);

# If you don't have some download manager then you can remove these
profile.set_preference("browser.download.manager.showWhenStarting",False)
profile.set_preference("browser.download.manager.useWindow", False);
profile.set_preference("browser.download.manager.focusWhenStarting", False);
profile.set_preference("browser.download.manager.alertOnEXEOpen", False);
profile.set_preference("browser.download.manager.showAlertOnComplete", False);

driver=webdriver.Firefox(firefox_profile=profile,executable_path="<>")

driver.get("https://dibbs2.bsm.dla.mil/Downloads/RFQ/Archive/ca210731.zip")
driver.find_element_by_id("butAgree").click()

在这里,我们设置一些配置文件来禁用弹出下载对话框

它在最新版本的Firefox和3.141.0版本的selenium中工作得非常好

相关问题 更多 >

    热门问题