如何用Selenium提取img的src属性?Base64解码显示空白图问题
问题解决:Selenium获取img src得到Base64空白图
问题根源
网站采用懒加载机制(img标签带有felazyload属性):页面初始加载时,img的src是占位用的Base64空白图,只有当元素进入浏览器视口后,才会替换为真实的图片URL。Selenium默认加载页面时,目标元素可能不在视口内,因此未触发懒加载,导致获取到的是占位图。
解决方案
方案1:滚动到元素触发懒加载
通过代码将目标元素滚动到视口,触发浏览器加载真实图片,再获取src:
import base64 from io import BytesIO from PIL import Image from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait def base64_to_image(base64_string): image_data = base64.b64decode(base64_string) image = Image.open(BytesIO(image_data)) return image options = Options() options.add_argument("--disable-notifications") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option("useAutomationExtension", False) driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) driver.implicitly_wait(10) driver.set_window_size(1200, 800) driver.get('https://www.migros.com.tr/sut-kahvaltilik-c-4?sayfa=1') # 定位目标图片元素 elem = driver.find_element(By.XPATH,"/html/body/sm-root/div/main/sm-product/article/sm-list/div/div[4]/div[2]/div[4]/sm-list-page-item[1]/mat-card/div[1]/fe-product-image/a/img") # 滚动到元素位置,触发懒加载 driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", elem) # 等待src替换为真实URL(不再是Base64格式) WebDriverWait(driver, 10).until( lambda d: "data:image/png;base64," not in elem.get_attribute("src") ) # 获取真实图片链接 real_src = elem.get_attribute("src") print(real_src) # 直接下载并展示真实图片(替代Base64解码步骤) import requests response = requests.get(real_src) with open("product.jpg", "wb") as f: f.write(response.content) Image.open("product.jpg").show()
方案2:直接读取懒加载存储的真实URL属性
多数懒加载会将真实图片链接存储在data-src、data-original这类自定义属性中,可直接获取:
# 替换获取src的代码 real_src = elem.get_attribute("data-src") # 需根据实际HTML属性调整
关键说明
- 增大浏览器窗口尺寸可减少滚动操作,但滚动到元素是更可靠的触发懒加载方式。
- 显式等待能精准确保图片加载完成,避免过早获取占位图。
- 直接请求真实URL下载图片,比处理Base64占位图更高效。
内容的提问来源于stack exchange,提问作者hepburda
相关产品推荐
相关产品推荐

