-1

wen I apply the method Scroll to a whole window it works fine:

driver.execute_script("window.scrollTo(0, 1000);")

The problem is that I must apply it to a DIV so I get the Div and then apply Scroll like this:

    myDiv = self.driver.find_elements(By.XPATH, '//div[contains(@class,"ODSEW-ShBeI NIyLF-haAclf gm2-body-2")]')
myDiv..execute_script("window.scrollTo(0, 1000);")

but it do nothing. Any idea?

bartoro
  • 7
  • 3

1 Answers1

0

Assuming your div is scrollable, this should work:

myDiv = self.driver.find_element(By.XPATH, '//div[contains(@class,"ODSEW-
self.driver.execute_script("arguments[0].scroll(0, 1000)", myDiv)

If the element is not scrollable:


# thanks to https://stackoverflow.com/a/35940276/5226491
find_scrollable_parent_script = '''
function getScrollParent(node) {
  if (node == null) {
    return null;
  }

  if (node.scrollHeight > node.clientHeight) {
    return node;
  } else {
    return getScrollParent(node.parentNode);
  }
}

return getScrollParent(arguments[0]);
'''
myDiv = self.driver.find_element(By.XPATH, '//div[contains(@class,"ODSEW-ShBeI NIyLF-haAclf gm2-body-2")]')
scrollable = self.driver.execute_script(find_scrollable_parent_script, myDiv)
self.driver.execute_script("arguments[0].scroll(0, 1000)", scrollable)
Max Daroshchanka
  • 2,698
  • 2
  • 10
  • 14
  • Thank you, I get this error:Message: javascript error: arguments[0].scroll is not a function (Session info: chrome=97.0.4692.99) – bartoro Jan 31 '22 at 15:58
  • Sorry, my issue. In the first line should be `driver.find_element` instead of `driver.find_elements` – Max Daroshchanka Jan 31 '22 at 16:41
  • Now there is no error but no scroll. I guess the problem is that there are one div within other and other and so on.... There are like 20 and try all but no scroll at all. When I use it in a "flat" window it scrolls so not sure what the issue is. For sure you can scroll when in the site so it must be possible. – bartoro Feb 01 '22 at 13:07
  • @bartoro I think scroll doesn't work because the element is not scrollable. So, try to find the first scrollable parent for this element `'//div[contains(@class,"ODSEW-ShBeI NIyLF-haAclf gm2-body-2")]'`. This post might help: https://stackoverflow.com/a/35940276/5226491. You can invoke this function in browser console, or execute with webdriver (in this case you also have to pass `myDiv` to script like `arguments[0]` ). – Max Daroshchanka Feb 01 '22 at 13:12
  • @bartoro I've updated the answer again. – Max Daroshchanka Feb 01 '22 at 13:17