首页 > 解决方案 > Selenium / Python:为什么所有检测到的元素在y:1或y:0的y位置都有坐标?

问题描述

我的元素坐标似乎都停留在 y=0 和 y=1,因此我无法滚动到它们。我正在使用 Python 进行编码,并获得了网站中的元素列表:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains 
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

bot = webdriver.Firefox(executable_path=r'\geckodriver.exe')
bot.get('URL')
bot.execute_script('window.scrollTo(0, document.body.scrollHeight)')
time.sleep(1)
xpath = "//div[@data-testid='something']"  
el = bot.find_elements_by_xpath(xpath)

我正在尝试滚动到每个元素:

coords = []
print("Getting coords")
for x in range(len(el)):
    coords.append(el[x].location_once_scrolled_into_view)
for x in coords:
    print(x)
for x in range(len(coords)):
    print(x)
    bot.execute_script('window.scrollTo({}, {});'.format(coords[x]['x'], coords[x]['y']))
print("Done")

我的示例输出是:

length of elements is: 28
Getting coords
{'x': 622, 'y': 1}
{'x': 622, 'y': 0}
{'x': 622, 'y': 1}
...

编辑:这个问题被否决了。我没有解释早期的尝试,但我猜反对票可能是由于缺乏研究。我正在编辑这个问题以显示我的所有尝试:

尝试 1:元素可能不可见。尝试等到元素可点击/可见

wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))

结果/输出 (1):部分成功。运行 element_to_be_clickable 后,最后两个元素具有实际的 y 坐标(如果我不使用它,所有 y 坐标都是 0 或 1)。我认为问题可能出在 element_to_be_clickable - 是否可以为发现的 28 个元素中的每一个运行这个?:

{'x': 622, 'y': 77}
{'x': 621, 'y': 168}

尝试 2:尝试确保所有检测到的元素都是可点击的 - 如果可行,请将其包含在 while 循环中。

wait.until(EC.element_to_be_clickable(el[1]))

结果/输出(2):TypeError:*后的find_element()参数必须是可迭代的,而不是FirefoxWebElement

尝试 3:可能没有足够的元素存在。尝试加载所有元素。

while True:               
        wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
        elements = bot.find_elements_by_xpath(xpath)
        counter = len(elements)
        print(counter)
        if counter > 10:
            break

结果/输出 (3):没有变化。增加计数器最小值只会返回更多带有 y:1 或 y:0 的坐标

尝试 4:给元素足够的时间来完成加载

import time
time.sleep(5)

结果/输出 (4):无变化

Edit2尝试 5检查所有元素的可见性

wait.until(EC.visibility_of_all_elements_located((By.XPATH, xpath)))

结果/输出 (5):无变化 - 仅返回坐标 y = 0 和 y = 1 的结果

标签: pythonselenium

解决方案


问题是 GeckoDriver 0.27 在运行 .location_once_scrolled_into_view 时不会滚动到 FireFox v79 和 Selenium 3.141 中的元素(至少是可见的)。解决方案是改用 .location 以便可以查看 DIV 元素(此处为 Selenium Python 文档):

    for x in range(len(el)):
        coords.append(el[x].location)

结果:

17
length of elements is: 17
Getting coords
{'x': 617, 'y': 4786}
{'x': 622, 'y': 4958}
{'x': 617, 'y': 5049}
{'x': 622, 'y': 5356}
{'x': 622, 'y': 5923}
...

推荐阅读