You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Selenium抓取OpenSea角色的链接与图片?求代码修正

OpenSea Meebits藏品页面抓取代码修复方案

原代码核心问题

  • 元素定位错误:
    • profiles 使用find_element(单数)仅能获取第一个网格元素,需改用find_elements(复数)遍历所有藏品卡片
    • 子元素XPATH用了绝对路径/div,应改为相对路径./div基于当前卡片定位
    • art_link用LINK_TEXT配合XPATH语法完全错误,需直接定位藏品卡片内的<a>标签提取href属性
  • 循环逻辑混乱:
    • 藏品相关变量(art_name、art_price等)在循环内定义,导致外部循环无法访问
    • art_link循环中错误追加n.text(藏品名称)而非链接地址
  • 缺失图片抓取逻辑:原需求需抓取角色图片,但原代码未涉及该部分

修正后的完整代码

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
import time

# 初始化浏览器
driver = webdriver.Chrome()
target_url = "https://opensea.io/collection/meebits?search[sortAscending]=false&search[sortBy]=FAVORITE_COUNT"
driver.get(target_url)
# 等待页面核心元素加载完成(替代固定sleep更可靠)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@role="grid"]')))

# 初始化存储列表
collection_name = []
collection_desc = []
art_names = []
art_prices = []
art_links = []
art_image_urls = []

# 抓取藏品集名称与描述
coll_name = driver.find_element(By.XPATH, '//h1')
collection_name.append(coll_name.text)
coll_desc = driver.find_element(By.XPATH, '//div[@class="sc-1xf18x6-0 sc-1aqfqq9-0 sc-1y1ib3i-7 haVRLx dfsEJr eGsklH"]')
collection_desc.append(coll_desc.text)

# 遍历所有藏品卡片
profiles = driver.find_elements(By.XPATH, '//div[@role="grid"]/div')
for profile in profiles:
    # 相对路径定位当前卡片内的元素
    art_name = profile.find_element(By.XPATH, './div[@class="sc-7qr9y8-0 sc-dw611d-1 iUvoJs fcpvjL"]')
    art_names.append(art_name.text)
    
    art_price = profile.find_element(By.XPATH, './div[@class="sc-7qr9y8-0 iUvoJs Price--amount"]')
    art_prices.append(art_price.text)
    
    # 提取藏品完整链接
    art_link = profile.find_element(By.XPATH, './a').get_attribute('href')
    art_links.append(art_link)
    
    # 提取藏品图片链接
    art_image = profile.find_element(By.XPATH, './a/div/img').get_attribute('src')
    art_image_urls.append(art_image)
    
    time.sleep(0.5)  # 降低请求频率,避免触发反爬限制

# 打印结果验证
print("藏品集名称:", collection_name)
print("藏品集描述:", collection_desc)
print("藏品名称列表:", art_names)
print("藏品价格列表:", art_prices)
print("藏品链接列表:", art_links)
print("藏品图片列表:", art_image_urls)

# 关闭浏览器
driver.quit()

关键修复说明

  • 用WebDriverWait替代固定time.sleep,确保元素加载完成后再操作,提升代码稳定性
  • 藏品卡片遍历采用find_elements(复数)获取所有卡片,子元素用相对路径./定位,避免全局定位混乱
  • 直接从<a>标签提取href属性获取藏品链接,从<img>标签提取src属性获取图片链接
  • 统一变量命名规范,避免变量名重复或逻辑混乱
  • 添加请求间隔,降低被OpenSea反爬机制限制的风险

内容的提问来源于stack exchange,提问作者Muhammad Tayyab Shah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:24:23