pythonselenium-webdriverwebautomation

How To Scroll a Sub Menu in a Main Facebook Page Using Python Selenium


I want to scroll inside my chat list in Messenger web, but I can't get it to work. Here's my code:

chatList = driver.find_elements(By.XPATH,'//div[@class="x1n2onr6"]')

for chat in chatList:
    driver.execute_script("arguments[0].scrollIntoView();", chat)

I've tried various things, such as:


Solution

  • So what I believe is happening here is there are no new values to scroll into view. When you run the for loop on the chatlist it will run only on the elements found in the first instance.

    in order to get around this you will have to run a for loop within a while loop.

    first you will have to make sure that the chatlist is the area containing the child elements which contain the text.

    from time import sleep
    
    recheck_limit = 3
    
    while True:
        
        try:
            # Search through a scroll wrapper and get descendants
    
            chatList = driver.find_elements(By.XPATH,'
                 [GET THE SCROLL AREA]/descendant:://div[@class="x1n2onr6"]')
    
        except NoSuchElementException:
            break
    
        try:
            # check if chatlist has repeated and break loop if it has.
    
            if last_set == chatList: 
                recheck_limit -= 1
                sleep(0.5)
                continue
                
                if recheck_limit == 0:
                    break
    
        except UnboundLocalError as em:
            pass
    
        for chat in chatList:
    
            print(chat)
    
            try:
                driver.implicitly_wait(5)
    
                chat = driver.execute_script("arguments[0].scrollIntoView();", chat)
            except StaleElementReferenceException:
                pass
    
        # save chatlist to last_set variable (to check if repeated.)
    
        last_set = chatList
    

    This has worked for me in the past.