【发布时间】:2020-02-04 16:51:22
【问题描述】:
我有一个问题在此处以某种方式进行了讨论 ([python][selenium] on-screen position of element),但目前并没有达到我想要实现的目标。
我的目标如下: element.location 给出浏览器中元素左上角的位置。我有一个网站,即使它可能不是一个好的硒实践,我也希望能够完全根据它的位置点击这样的元素,因为它从来没有改变过,可能永远也不会改变。 假设 element.location 给出 {'x': 253, 'y': 584},这是我迄今为止尝试的代码,没有运气
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver.maximize_window()
url = "https://learn.letskodeit.com/p/practice"
driver.get(url)
open_window_elem = driver.find_element_by_id("openwindow")
# from wherever the mouse is, I move to the top left corner of the broswer
action = ActionChains(driver)
action.move_by_offset(-1000, -1000)
action.click()
action.perform()
y_coordinate = open_window_elem.location["y"]
x_coordinate = open_window_elem.location["x"]
action = ActionChains(driver)
action.move_by_offset(x_coordinate, y_coordinate)
action.click()
action.perform()
当我运行这段代码时没有任何反应。我会打开一个新窗口。 有人可以帮忙吗?
【问题讨论】:
-
当您有其他防故障选项来访问定位器时,为什么还要使用定位?
-
@Abhishek_Mishra 好问题。我正在创建一个自动化脚本,该脚本将首先尝试使用普通定位器获取和单击元素,但由于元素 HTML 语法不断变化,我正在构建第二种方法来完全基于其位置单击该元素,以便当DOM 发生了变化,至少我的脚本一直在工作,让我有时间修复我的代码(基于页面对象模型)
-
获取坐标需要首先获取WebElement,万一DOM被改变,它只会在那里失败。看看这里:stackoverflow.com/questions/6775351/…
-
元素的位置永远不会改变。我知道它的 x,y 坐标总是相同的。这就是为什么,无论 DOM 是什么,我都希望 selenium 点击屏幕上的那个 x,y 点
标签: python selenium-webdriver position selenium-chromedriver