我正试图使用像素位置在图表上拖动光标。尽管在调用第二个选项后,光标不再在屏幕上。
我尝试action_reset((将值重置为0,然后调用move_by_offset(290400(,但失败了。
我试着添加move_by_offset(10,0(。但这也失败了。我已经阅读了文档,但不知道哪里出了问题?
在开始下一步行动之前,我应该实施另一种方法吗?
from selenium import webdriver
action = webdriver.ActionChains(driver)
# setup automation
action.move_by_offset(280, 400) # 11px to the right, 20px to bottom
action.perform()
driver.save_screenshot("screenshot_4.png")
action.move_by_offset(290, 400) # 11px to the right, 20px to bottom
action.perform()
driver.implicitly_wait(11)
driver.save_screenshot("screenshot_5.png")
首先,move_by_offset根据光标的当前位置移动光标。
action.move_by_offset(280, 400) # This actually moved your cursor 280 to the right
至于为什么简单地使用10失败。。。它可能是与光标最初所在的位置相关的许多事情。
首先,确保最大化你的驱动程序窗口,因为如果窗口太小,你的偏移可能会超过你的目标。
如果要在图表中移动光标,首先移动到图表所在的元素会更容易。我个人只使用move_to_element_with_offset将光标移动到图表元素的左上角。然后使用元素的宽度循环作为上限。
hover_area_css = "#some css selector"
hover_area_element = driver.find_element(By.CSS_SELECTOR,hover_area_css)
""" alternatively hover_area_element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, hover_area_css))
)"""
# this goes to the upper left corner of the element, and goes to the right one px.
# I also go slightly downward in case the hover action doesn't occur at the boundary
actions = ActionChains(driver).move_to_element_with_offset(hover_area_element, 1, 2)
actions.perform()
# you might need to sleep a bit prior to continuing
time.sleep(2)
# the size attribute contains dimension information of the element
width = hover_area_element.size["width"]
x_scroll = ActionChains(driver)
for i in range(width):
try:
# some func that captures the tooltip data for example
# handle when tooltip no longer appears (you're off the chart)
except NoSuchElementException:
break
# you can also take the width and divide it by the number of x-axis ticks in the chart and use that as the offset for a rough estimate.
x_scroll.move_by_offset(1,0)
x_scroll.perform()