【问题标题】:How to find correct element location in selenium python如何在 selenium python 中找到正确的元素位置
【发布时间】:2019-04-18 10:15:51
【问题描述】:

我正在尝试在 selenium 中找到一个元素的正确位置,但这给我带来了一些麻烦,这是我的代码


from selenium import webdriver
from pynput.mouse import Button, Controller as MouseController
mouse = MouseController()

driver = webdriver.Chrome()

driver.maximize_window()
driver.set_page_load_timeout(30)

driver.get("https://stackoverflow.com/")
element = driver.find_element_by_xpath('//*[@id="mainbar"]/div[1]/h1')
x, y = element.location["x"], element.location["y"]

mouse.position = x, y

但我不明白为什么它返回的位置与正确的元素位置不同

【问题讨论】:

  • 你想完成什么?您预期的元素位置是什么?
  • 我期待的元素位置是链接上写“热门问题”的一角
  • 可能是x, y = element.location["x"]+element.size["width"]/2, element.location["y"]+element.size["height"]/2 ?

标签: python selenium


【解决方案1】:

Pynput 会根据屏幕大小转到绝对坐标,而从 selenium 获得的坐标是相对于浏览器窗口的。

为了解决这个问题,您需要在计算 y 坐标时考虑浏览器导航栏的大小:

browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')
x, y = element.location["x"], element.location["y"] + browser_navigation_panel_height

这个post 为我指出了一个解决方案。

注意:此解决方案仅在浏览器窗口最大化时有效

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2019-04-24
    • 2019-04-22
    • 2022-12-29
    • 2021-08-27
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多