问个 Python selenium 的问题

166 天前
 guoguobaba
```python
for x, y in param:
center_x = int(x) - div_size['width'] / 2
center_y = int(y) - div_size['height'] / 2
logging.info("click at (%.2f, %.2f)" % (center_x, center_y))
action_chains.move_to_element_with_offset(element, center_x,center_y).click().perform()
time.sleep(random.randint(0, 10) / 10)
```
按文档说 move_to_element_with_offset 是 Move the mouse by an offset of the
specified element. Offsets are relative to the top-left corner of the element.
是以左上为原点,但是我这里必须以 element 中心为原点才能成功呢?
956 次点击
所在节点    Python
1 条回复
jackaluo
166 天前
根据您的描述,您想要在 Selenium 中使用 move_to_element_with_offset 方法,但是您希望以元素的中心点作为原点,而不是左上角。默认情况下,move_to_element_with_offset 方法确实是以元素的左上角作为原点的。

如果您想以元素的中心为原点移动鼠标,您可以自己计算中心点的坐标,然后将偏移量设置为中心点与目标点之间的差值。这是一个示例代码:
for x, y in param:
center_x = int(x)
center_y = int(y)
logging.info("click at (%.2f, %.2f)" % (center_x, center_y))

# 计算偏移量,使其相对于元素中心
offset_x = center_x - element.size['width'] / 2
offset_y = center_y - element.size['height'] / 2

action_chains.move_to_element_with_offset(element, offset_x, offset_y).click().perform()
time.sleep(random.randint(0, 10) / 10)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/998109

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX