当前位置:   article > 正文

Python使用selenium下载百度图片_selenium通过url下载图片

selenium通过url下载图片

Python使用selenium下载百度图片

import os
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By


def init(): #初始化浏览器
    save_path = r"D:\Deskbook\image" #下载路径
    os.makedirs(save_path, exist_ok=True)  # 确保输出文件夹存在
    timeout = 2 #超时等待时间
    url = "https://image.baidu.com/search/detail?" #网页url

    #编辑配置
    prefs = {
        "profile.default_content_settings.popups": 0, #防止保存弹窗
        "download.default_directory": save_path, #修改默认下载路径
        "profile.default_content_setting_values.automatic_downloads": 1 #允许多文件下载
    }

    chrome_options = webdriver.ChromeOptions()
    # 添加配置
    chrome_options.add_experimental_option("prefs", prefs)
    # 修改 windows.navigator.webdriver, 防机器人识别机制, selenium 自动登陆判别机制
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    # 禁用启用blink运行时的功能
    chrome_options.add_argument("--disable-blink-features=AutomationControlled")

    driver = webdriver.Chrome(options=chrome_options)
    print("启动浏览器")
    # 超时等待, 隐性等待
    driver.implicitly_wait(timeout)
    driver.get(url=url)
    print("打开网页")

    return driver


def find(driver,xp): #捕获网页元素
    try:
        element = driver.find_element(By.XPATH,xp)
        return element
    except Exception as e:
        print(xp+" 捕获失败")
        raise e

def work(driver):
    driver.switch_to.default_content()
    download = find(driver,'//*[@class="bar-btn btn-download"]') # 下载键
    download.click()

    sleep(1)

    img_next = find(driver,'//*[@class="img-next"]') # 切换下一张图像
    img_next.click()

if __name__ == "__main__":
    driver = init()
    for i in range(300):
        work(driver)

    driver.quit()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/801157
推荐阅读
相关标签
  

闽ICP备14008679号