python+selenium+chrome批量文件下载并自动创建文件夹

实现效果:通过url所绑定的关键名创建目录名,每次访问一个网页url后把文件下载下来

代码:

其中 data[i][0]、data[i][1] 是代表 关键词(文件保存目录)、网站链接(要下载文件的网站)

def getDriverHttp():
    for i in range(reCount):
        # 创建Chrome浏览器配置对象实例
        chromeOptions = webdriver.ChromeOptions()
        # 设定下载文件的保存目录为d盘的tudi目录,
        # 如果该目录不存在,将会自动创建
        prefs = {"download.default_directory": "e:\\tudi\\{0}".format(data[i][0]), "profile.default_content_setting_values.automatic_downloads":1}
        # 将自定义设置添加到Chrome配置对象实例中
        chromeOptions.add_experimental_option("prefs", prefs)
        # 启动带有自定义设置的Chrome浏览器
        # driver = webdriver.Chrome(executable_path="e:\\chromedriver", chrome_options=chromeOptions)
        driver = webdriver.Chrome(chrome_options=chromeOptions)


        driver.get(data[i][1])


        info2 = re.findall(r'<a href="#" onclick="(.*?)" cssclass="xz_pic">', driver.page_source, re.S)
        print(len(info2))
        for js in info2:
            driver.execute_script(js)


def main():
    getDriverHttp()

注意:python 使用selenium下载文件时,chrome会提示是否下载多个文件(Download multiple files)

prefs = {"download.default_directory": "e:\\tudi\\{0}".format(data[i][0]), "profile.default_content_setting_values.automatic_downloads":1}

设置允许多个文件下载。

猜你喜欢

转载自blog.csdn.net/weixin_40096730/article/details/88978151