Skip to main content
 首页 » 编程设计

Python 和 Selenium : firefox keep creating dialog boxes when downloading even if i set its preferences

2025年01月19日10java哥

我使用 selenium 和 firefox 网络驱动程序编写了一个程序。

def dowloadFile(link): 
    profile = webdriver.FirefoxProfile() 
    profile.set_preference('browser.download.folderList', 2) # custom location 
    profile.set_preference('browser.download.manager.showWhenStarting', False) 
    profile.set_preference('browser.download.dir', '/tmp') 
    profile.set_preference('browser.helperApps.neverAsk.saveToDisk',  
    'application/pdf') 
 
    driver = webdriver.Firefox(profile) 
    #driver.set_window_position(-10000,0) 
    driver.get(link) 
    s = BeautifulSoup(driver.page_source, "html.parser") 
    st=s.find('div',{"class":"bloc-docs-link bloc-250"}) 
    #print("hadiii ST: "+str(st)) 
    x=st.find('a') 
    fm=x.get('href') 
    fm="https://www.marchespublics.gov.ma/"+fm 
    driver.get(fm) 
    driver.quit() 

我的函数将链接作为参数,然后获取该链接并最终找到另一个下载文件的链接。 我的问题是,即使我设置了我的 firefox 的首选项,它在下载时总是显示对话框,以确认我是否要保存它!我不知道该怎么做才能在没有此对话框的情况下下载文件。

请帮忙。提前谢谢你。

请您参考如下方法:

我也遇到过这个问题。我只是这样做了。注意:它确实需要更多时间,所以如果您要下载大量文件,这可能不值得。否则,这将起到作用。

创建一个准备好在对话框中使用的警报对象,例如:

alert = driver.switch_to_alert() 

导入预期条件:

from selenium.webdriver.support import expected_conditions as EC 

然后,创建一个函数,指示浏览器等待,直到提示预期的条件(警报)。

WebDriverWait(browser, 3).until(EC.alert_is_present() 
except TimeoutException: 

最好将此作为 try/except block ,但不是强制性的。

然后,在 selenium 控制了警报窗口后,只需使用警报对象的“接受”方法来确认下载:

alert.accept() 

函数看起来像这样:

    try: 
        alert = driver.switch_to_alert() 
        alert_wait() 
        alert.accept() 
    except print('No alertfound') 

此外,我强烈建议为此使用 requests/BeautifulSoup 模块,这样您就不必渲染浏览器并体验浏览大量网页所带来的延迟。 requests 模块在幕后完成这一切。如果您需要在下载前输入密码,这会变得很棘手。如果没有,BeautifulSoup 库非常适合抓取标签/href,将它们收集在一个列表中,然后使用类似的 requests.get() 方法一个一个地遍历它们。

事实上,上次遇到这个问题时,我使用了requests模块而不是selenium,并且自动接受了警报窗口。闪电也很快。