Search code examples
javascriptpythonseleniumgoogle-chromejs-scrollby

scrollBy() invoked through execute_script is not working on chrome store page using Selenium and Python


I'm using selenium with python 3 and Chrome driver. I'm trying to perform a scroll in a chrome store URL.

This one: https://chrome.google.com/webstore/detail/online-game-zone-new-tab/abalcghoakdcaalbfadaacmapphamklh

No matter what I tried - the site doesn't scroll. Tried running "window.scrollBy" and "window.scrollTo". Tried clicking on "body" first, and other elements - nothing.

current code:

driver.maximize_window()
driver.get(url)
time.sleep(4)
driver.execute_script("window.scrollBy(0, 500)")

What could be the problem? I don't want to send a "down" key or "page down" since I believe I'll need to be more precise.


Solution

  • If you observe the chrome store page the page have a header that is fixed to the top of the page. So when the window object is invoked, the focus jumps at the top of the page, leaving the document behind the fixed header.

    You can find a detailed discussion in offsetting an html anchor to adjust for fixed header

    Additionally, at times ChromeDriver is pretty fast and the scrollTo() action fires before Chrome's default scroll to html anchor event. In these cases, a possible solution would be to induce some delay as follows:

    setTimeout(function() {window.scrollTo(0, y);},1)
    

    You can find a detailed discussion in JavaScript issue with scrollTo() in Chrome

    As an alternative, to perform a scroll within the chrome store URL you need to induce WebDriverWait for the visibility_of_element_located() of your choice and you can use the following Locator Strategy based solution:

    • Using scrollIntoView():

      driver.get('https://chrome.google.com/webstore/detail/online-game-zone-new-tab/abalcghoakdcaalbfadaacmapphamklh')
      driver.execute_script("arguments[0].scrollIntoView();", WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='Related']"))))
      
    • Browser Snapshot:

    Related