如何用Python Selenium抓取Blur平台NFT借贷列表的任意行数据?
解决Blur平台NFT借贷列表的Selenium数据提取问题
问题概述
需要开发机器人识别Blur平台上符合特定条件的NFT借贷列表(如LTV≤80%、APY>100%),已实现页面导航,但提取表格数据时遇到困难,希望将借贷列表提取为字典数组(每个元素包含名称、状态、借款金额、LTV、APY),并寻求按行提取的简便方法。
现有代码问题分析
之前提取APY失败的核心问题是CSS选择器错误:
- 原代码使用
'Text-sc-m23s7f-0 hAGCAO',正确的多类名选择器应该用点连接:.Text-sc-m23s7f-0.hAGCAO - Blur的前端类名是动态生成的,可能随时变化,更可靠的方式是结合元素结构或属性定位,而非依赖动态类名。
按行提取的解决方案
通过定位所有贷款行元素,遍历每行并提取对应字段,是更高效的方式。步骤如下:
- 用显式等待替代
time.sleep,确保元素加载完成后再操作 - 定位所有贷款行的容器元素
- 遍历每行,在该行内分别提取名称、状态、借款金额、LTV、APY
- 将每行数据整理为字典,存入列表
完整代码示例
import selenium from selenium.webdriver.common.by import By from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time path = "/Users/#########/Desktop/chromedriver-mac-arm64/chromedriver" # 配置Chrome选项 options = Options() options.add_experimental_option("detach", True) options.add_argument("disable-infobars") # 初始化WebDriver service = Service(path) driver = webdriver.Chrome(service=service, options=options) driver.maximize_window() # 打开Blur Beanz借贷页面 driver.get("https://blur.io/eth/collection/beanzofficial/loans") # 显式等待并切换到"Loans"标签 wait = WebDriverWait(driver, 10) loan_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//nav[contains(@class, 'tabs')]/button[2]"))) loan_button.click() # 等待贷款列表加载完成 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "[data-testid='loan-item']"))) # 提取所有贷款行 loan_rows = driver.find_elements(By.CSS_SELECTOR, "[data-testid='loan-item']") loan_list = [] for row in loan_rows: # 提取每行数据 try: name = row.find_element(By.CSS_SELECTOR, "[data-testid='loan-item-name']").text status = row.find_element(By.CSS_SELECTOR, "[data-testid='loan-item-status']").text amount = row.find_element(By.CSS_SELECTOR, "[data-testid='loan-item-amount']").text ltv = row.find_element(By.CSS_SELECTOR, "[data-testid='loan-item-ltv']").text apy = row.find_element(By.CSS_SELECTOR, "[data-testid='loan-item-apy']").text # 整理为字典 loan_dict = { "名称": name, "状态": status, "借款金额": amount, "LTV": ltv, "APY": apy } loan_list.append(loan_dict) except Exception as e: print(f"提取行数据失败: {e}") continue # 筛选符合条件的借贷(LTV≤80% 或 APY>100%) filtered_loans = [] for loan in loan_list: # 处理LTV数值(去除%符号并转成浮点数) ltv_value = float(loan["LTV"].replace("%", "")) if loan["LTV"] else 0 # 处理APY数值(去除%符号并转成浮点数) apy_value = float(loan["APY"].replace("%", "")) if loan["APY"] else 0 if ltv_value <= 80 or apy_value > 100: filtered_loans.append(loan) # 输出结果 print("所有借贷数据:") for loan in loan_list: print(loan) print("\n符合条件的借贷数据:") for loan in filtered_loans: print(loan) # 关闭浏览器 time.sleep(5) driver.quit()
关键优化点
- 使用
data-testid属性定位元素:Blur页面部分元素带有data-testid,这是前端预留的测试标识,比动态类名更稳定 - 显式等待:通过
WebDriverWait确保元素可交互后再操作,避免因页面加载慢导致的元素未找到错误 - 异常处理:遍历行时加入异常捕获,避免某一行提取失败导致整个程序中断
- 数据筛选:自动过滤出符合LTV或APY条件的借贷条目
内容的提问来源于stack exchange,提问作者number2patrician
相关产品推荐
相关产品推荐

