
本文旨在提供一种使用 Selenium 和 Python 下载由 JavaScript 动态渲染的网页图片的方法。 针对图片URL为标准URL或Base64编码的情况,分别提供解决方案。通过结合 Selenium 的页面加载能力和 requests 库或 base64 库的数据处理能力,可以有效地从网页中提取并保存图片资源。本文提供详细的代码示例和解释,帮助开发者轻松实现图片下载功能。
很多网页使用 JavaScript 动态加载图片,这使得直接通过 requests 库获取图片变得困难。Selenium 可以模拟浏览器行为,等待 JavaScript 执行完毕,从而获取完整的页面内容,包括动态加载的图片。
以下是一个使用 Selenium 和 Python 下载网页中 JavaScript 渲染的图片的详细教程。
前提条件
立即学习“Java免费学习笔记(深入)”;
安装 Python: 确保你已经安装了 Python 3.6 或更高版本。
安装 Selenium: 使用 pip 安装 Selenium 库:
pip install selenium
安装 requests: 用于下载标准 URL 的图片:
pip install requests
安装 Chrome WebDriver: 下载与你的 Chrome 浏览器版本匹配的 ChromeDriver,并将其添加到系统 PATH 环境变量中。你也可以指定 ChromeDriver 的路径。
代码示例
以下代码演示了如何使用 Selenium 下载网页中的图片,包括处理标准 URL 和 Base64 编码的图片:
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC
import warnings
import base64
import requests
warnings.filterwarnings("ignore", category=DeprecationWarning)
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
# chromedriver.exe 路径根据你的实际情况修改
service = Service(executable_path='./chromedriver.exe')
driver = webdriver.Chrome(service=service, options=options)
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
wait = WebDriverWait(driver, 20, ignored_exceptions=ignored_exceptions)
image_url = """https://nrex.quickbase.com/db/bpumk9kh3?a=dbpage&pageID=80&rid=169453"""
driver.get(str(image_url))
wait.until(EC.presence_of_element_located((By.XPATH, "//div[@id='imageData']//a")))
driver.implicitly_wait(20)
data = driver.page_source
images = driver.find_elements(By.XPATH, "//img")
for i, image in enumerate(images):
    src = image.get_attribute('src')
    if src and src.startswith('http'):
        response = requests.get(src)
        if response.status_code == 200:
            with open(f'image_{i}.jpg', 'wb') as file:
                file.write(response.content)
    elif src and src.startswith('data:image'):
        base64_encoded_data = src.split(',')[1]
        with open(f'image_{i}.jpg', 'wb') as file:
            file.write(base64.b64decode(base64_encoded_data))
driver.quit()代码解释
导入必要的库:
配置 Chrome 选项:
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')初始化 WebDriver:
service = Service(executable_path='./chromedriver.exe') driver = webdriver.Chrome(service=service, options=options)
打开网页:
image_url = """https://nrex.quickbase.com/db/bpumk9kh3?a=dbpage&pageID=80&rid=169453""" driver.get(str(image_url))
等待元素加载:
wait.until(EC.presence_of_element_located((By.XPATH, "//div[@id='imageData']//a"))) driver.implicitly_wait(20)
查找图片元素:
images = driver.find_elements(By.XPATH, "//img")
遍历图片元素并下载:
for i, image in enumerate(images):
    src = image.get_attribute('src')
    if src and src.startswith('http'):
        response = requests.get(src)
        if response.status_code == 200:
            with open(f'image_{i}.jpg', 'wb') as file:
                file.write(response.content)
    elif src and src.startswith('data:image'):
        base64_encoded_data = src.split(',')[1]
        with open(f'image_{i}.jpg', 'wb') as file:
            file.write(base64.b64decode(base64_encoded_data))关闭浏览器:
driver.quit()
注意事项
总结
本文提供了一个使用 Selenium 和 Python 下载 JavaScript 渲染的图片的完整解决方案。通过结合 Selenium 的页面加载能力和 requests 库或 base64 库的数据处理能力,可以有效地从网页中提取并保存图片资源。在实际应用中,需要根据具体情况进行调整和优化,例如处理异常、应对反爬虫机制等。
以上就是使用 Selenium 和 Python 下载 JavaScript 渲染的图片的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号