使用Python3和Selenium打造百度图片爬虫

开篇

本文的目的在于实现一个用来爬取百度图片的爬虫程序,因该网站不需要登录,所以相对来说较为简单。下面的爬虫程序中我写了比较多的注释,以便于您的理解。

准备

请确保电脑上已经安装了与chrome浏览器版本匹配的chromeDriver,且电脑中已经安装了python3和pip库。在上面的要求均已达到的情况下,请按照下面的顺序下载包:

pip install selenium

pip install openpyxl

pip install pandas

代码实现

python 复制代码
import os
import base64
import requests
import time
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化WebDriver的方法
def setup_driver(chrome_driver_path, chrome_executable_path):
    # 创建一个Options实例,用来配置Chrome浏览器的启动选项
    options = Options()
    # 启动浏览器时窗口最大化
    options.add_argument("--start-maximized")
    # 设置chrome浏览器的二进制位置
    options.binary_location = chrome_executable_path

    # 返回一个webdriver实例
    return webdriver.Chrome(service=Service(chrome_driver_path), options=options)

# 创建保存图片的目录
def create_save_directory(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)

# 下载图片
def download_img(url, filename):
    if url.startswith('data:image'):
        encoded = url.split(',', 1)[1]
        data = base64.b64decode(encoded)
        with open(filename, 'wb') as file:
            file.write(data)
    else:
        response = requests.get(url)
        if response.status_code == 200:
            with open(filename, 'wb') as file:
                file.write(response.content)

def main():
    # 设置chromedriver路径
    chrome_driver_path = r'F:\applications\chrome\chromedriver\chromedriver.exe'
    # 设置chrome.exe的路径
    chrome_executable_path = r'F:\applications\chrome\chrome\chrome.exe'

    # 初始化WebDriver
    driver = setup_driver(chrome_driver_path, chrome_executable_path)

    try:
        # 打开百度图片
        driver.get("https://image.baidu.com/")

        # 输入关键字并搜索
        search_box = driver.find_element(By.NAME, 'word')
        search_box.send_keys("狸花猫")
        search_box.send_keys(Keys.RETURN)

        # 等待页面加载
        WebDriverWait(driver, 19).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'img.main_img')))

        # 创建保存图片的文件夹
        save_directory = r'F:\codes\spider\baiduImgs'
        create_save_directory(save_directory)

        # 爬取图片
        img_cnt = 0
        while img_cnt < 100:
            # 获取当前页面所有图片元素
            imgs = driver.find_elements(By.CSS_SELECTOR, 'img.main_img')
            for img in imgs:
                if img_cnt >= 100:
                    break
                try:
                    src_url = img.get_attribute('src')
                    if src_url:
                        filename = os.path.join(save_directory, f'{img_cnt + 1}.jpg')
                        download_img(src_url, filename)
                        img_cnt += 1
                        print(f'Downloaded {filename}')
                except Exception as e:
                    print(f'Error downloading image: {e}')

            # 下滑页面以加载更多图片
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(3)

    finally:
        # 关闭浏览器
        driver.quit()

if __name__ == "__main__":
    main()

效果图

上面的代码即为百度图片爬虫的基本实现思路,希望能对您起到抛砖引玉的作用。

相关推荐
errorPage20 分钟前
Python空值判断避坑指南 + 图片定点缩放逻辑优化实战
python
郝学胜-神的一滴21 分钟前
Python方法类型详解:类方法、静态方法与实例方法
开发语言·python·程序人生
百***243730 分钟前
Grok-4.1 API进阶实战:Python项目集成、性能优化与异常处理全攻略
python·spring·性能优化
Trust yourself24332 分钟前
魔塔社区下载的大模型如何通过ollama部署到本地
python
码农胖虎-java33 分钟前
【java并发编程】从源码角度彻底理解 ForkJoinPool.commonPool
java·开发语言·python
毕设源码-朱学姐36 分钟前
【开题答辩全过程】以 基于Python淘宝电脑销售数据可视化系为例,包含答辩的问题和答案
python·信息可视化·电脑
三木彤38 分钟前
Scikit-learn 零基础,从安装到实战机器学习模型
python
Ulyanov39 分钟前
高级可视化技术——让PyVista数据展示更专业
开发语言·前端·人工智能·python·tkinter·gui开发
Sagittarius_A*1 小时前
图像滤波:手撕五大经典滤波(均值 / 高斯 / 中值 / 双边 / 导向)【计算机视觉】
图像处理·python·opencv·算法·计算机视觉·均值算法
开开心心_Every1 小时前
一键隐藏窗口到系统托盘:支持任意软件摸鱼
服务器·前端·python·学习·edge·django·powerpoint