一、前言
在Web开发和数据抓取过程中,有时需要自动下载并保存网页的截图。Selenium是一个强大的自动化测试工具,它支持多种浏览器,并能模拟用户行为,如点击、输入等。本文通过使用Selenium和ChromeDriver,实现了一个自动化下载网页截图的Python脚本。这个脚本不仅能访问指定的网页,还能根据需求保存网页截图,为网页分析和数据抓取提供了便利。
Chrome及驱动下载可参考博文:下载旧版本Chrome浏览器(QQ浏览器可能打不开,建议用IE、火狐等其他浏览器打开)
二、整体架构流程
-
导入所需的库:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.common.exceptions import WebDriverException, TimeoutException, NoSuchElementException import os
-
设置ChromeDriver的函数:
def setup_chrome_driver(driver_path, headless=True): chrome_options = Options() chrome_options.binary_location = r'.\Software and Drivers\chrome-win64\chrome.exe' chrome_options.add_argument('--headless' if headless else '') chrome_options.add_argument('--disable-gpu') service = Service(executable_path=driver_path) return webdriver.Chrome(