Python Selenium `move_by_offset` doesn't work

百般思念 提交于 2020-01-24 06:29:01

问题


Calling simple scrolling action with Python Selenium doesn't work:

driver = webdriver.Chrome()
driver.get('https://www.wikipedia.org/')
time.sleep(2)
actions = ActionChains(driver)
actions.move_by_offset(500, 500).perform()

For example function with moving to element, works Ok and Do scroll:

driver = webdriver.Chrome()
driver.get('https://www.wikipedia.org/')
time.sleep(2)

element = driver.find_element_by_css_selector(<Something>)
actions = ActionChains(driver)
actions.move_to_element(element).perform()

Calling moving to element with offset, doesn't work again:

driver = webdriver.Chrome()
driver.get('https://www.wikipedia.org/')
time.sleep(2)

element = driver.find_element_by_css_selector(<Something>)
actions = ActionChains(driver)
actions.move_to_element_with_offset(element, 500, 500).perform()

Any reasons why?


回答1:


Try to wait some seconds after moving mouse. For example, the following code to get screen captures in my CentOS7.3 host worked for me.

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument("--window-size=720,480")
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('/usr/bin/chromedriver', chrome_options=chrome_options, service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])

driver.get(url)
time.sleep(6)

ActionChains(driver).move_by_offset(50, 50).perform()
time.sleep(2)

filename="/tmp/Screenshots/uuid.png"
driver.save_screenshot(filename)



回答2:


It seems move_by_offset can not scroll a page, but it still can move the mouse to an offset from current mouse position.

To confirm we can try to do this:

driver = webdriver.Chrome()
driver.get('https://www.wikipedia.org/')
actions = ActionChains(driver)
actions.move_by_offset(300, 500).context_click().perform()

To scroll a page by offset we have to use js:

driver = webdriver.Chrome()
driver.get('https://www.wikipedia.org/')
driver.execute_script('window.scrollBy(0, 500)')  # x=0, y=500


来源:https://stackoverflow.com/questions/52433411/python-selenium-move-by-offset-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!