Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium `move_by_offset` doesn't work

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?

like image 621
GensaGames Avatar asked Oct 17 '22 13:10

GensaGames


2 Answers

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
like image 182
Artemiy Rodionov Avatar answered Oct 21 '22 07:10

Artemiy Rodionov


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)
like image 43
Batter Avatar answered Oct 21 '22 07:10

Batter