You need to enable JavaScript to run this app. 使用Python Selenium爬取指定站点商品图片链接时无法正常打印结果
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Selenium爬取指定站点商品图片链接时无法正常打印结果

代码提取失败的核心原因及修正方案

常见踩坑点

  • 硬匹配条件过滤掉所有目标元素:写img定位语句时加了src=True的筛选,同时要求类名完全匹配product-image-photo lazy。该站点商品图采用懒加载逻辑,真实图片链接不会初始写入src属性,且img类名会在渲染时动态追加其他值,完全匹配的条件加上src属性筛选,会直接把所有符合条件的img元素过滤为None,循环内拿不到有效元素。
  • 固定等待时长不足以完成页面渲染:采用time.sleep(6)固定等待,该站点商品列表为动态加载逻辑,资源加载存在延迟,6秒经常不足以让所有商品DOM节点完成渲染,此时content = soup.find_all('li',class_='item product product-item')返回的是空列表,循环逻辑根本不会执行。
  • 多余配置引发进程冲突:代码里加了--remote-debugging-port=9222的配置,如果本地已有Chrome进程占用该端口,会导致Selenium启动的浏览器实例加载异常,进一步出现页面渲染不全的问题。

修正后的可运行代码

import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "https://www.junaidjamshed.com/womens/stitched.html?product_list_limit=30"

options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument(
    "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")

driver = webdriver.Chrome('F:/chromedriver', options=options)
try:
    driver.get(url)
    # 用显式等待替代固定sleep,确认商品节点渲染完成后再提取源码
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "li.item.product.product-item"))
    )
    pageSource = driver.page_source
    soup = BeautifulSoup(pageSource, 'html.parser')
    content = soup.find_all('li', class_='item product product-item')
    
    for items in content:
        # 用核心类名模糊匹配img元素,移除强制src属性的筛选
        image = items.find('img', class_='product-image-photo')
        if image:
            # 优先读取懒加载存储的真实图片地址,兜底读取默认src值
            real_img_link = image.get('data-src') or image.get('src')
            print(real_img_link)
finally:
    # 爬取完成后关闭浏览器实例,释放端口占用
    driver.quit()

调整说明

  • 移除了img定位时的src=True硬筛选,适配懒加载的DOM结构
  • 用核心类名做模糊匹配,避免动态追加的类名导致元素定位失败
  • 用显式等待替代固定时长sleep,保证页面核心节点渲染完成后再提取内容,避免拿到空列表
  • 提取图片链接时优先读取data-src属性中的真实地址,兜底兼容默认src值
  • 注释了易引发端口冲突的远程调试配置,避免浏览器启动异常

内容的提问来源于stack exchange,提问作者Mehre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 10:54:04