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

如何拆分多元素坐标列表为独立变量并定位同高度元素

问题修复与解决方案

一、修复获取元素坐标列表并拆分x、y的代码

原代码存在三个关键错误:

  • 变量名拼写错误:将elementlocation误写为location,导致无法正确添加坐标到列表
  • element.location返回的是字典类型(格式如{'x': 123, 'y': 456}),不能直接用split(",")拆分
  • 若要批量提取所有元素的x、y坐标,需遍历坐标列表逐个解析字典

修复后的代码:

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

# 修正XPATH:原HTML中"100"在div而非span内
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[text()='100']")))

element_coords = []
for element in elements:
    coords = element.location
    element_coords.append(coords)
    print(coords)  # 打印单个元素的坐标字典

# 批量拆分所有元素的x、y坐标
xs = [coord['x'] for coord in element_coords]
ys = [coord['y'] for coord in element_coords]
print("所有x坐标:", xs)
print("所有y坐标:", ys)

# 提取单个元素的x、y坐标(如果只需要第一个)
if element_coords:
    single_x = element_coords[0]['x']
    single_y = element_coords[0]['y']
    print("单个元素x,y:", single_x, single_y)

二、定位与"110"同一高度的文本为"1"的元素

根据HTML结构,"110"位于第一列的第2个位置(Python索引为1,XPATH索引从1开始对应2),同一高度的元素是后续每一列的第2个div。通过索引匹配定位最稳定:

# 1. 获取"110"在第一列的位置索引
target_index = None
first_column_divs = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located(
    (By.XPATH, "//div[@class='srb-Market25Wrapping gl-Market_General gl-Market_General-columnheader gl-Market_General-haslabels gl-Market_General-pwidth12-5']/div")
))
for idx, div in enumerate(first_column_divs):
    if div.text == '110':
        target_index = idx
        break

# 2. 定位后续列中对应位置、文本为"1"的元素
if target_index is not None:
    target_elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located(
        (By.XPATH, f"//div[contains(@class, 'srb-Market375Wrapping')]/div[{target_index+1}]/span[text()='1']")
    ))
    for elem in target_elements:
        print("匹配元素:", elem.text, elem.location)

补充说明:

  • XPATH索引从1开始,因此Python的target_index需要加1才能对应正确位置
  • 相比通过y坐标范围匹配,索引匹配不受页面滚动、元素间距变化影响,稳定性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:21:31