Search code examples
pythonseleniumwhile-loopinfinite-loop

Selenium goes into infinite loop in Python


I am trying to scrape a website and fairly new to Python. I have managed to come up with below code. The problem however is it goes into an infinite loop after reaching the last page i.e Next button is greyed out. Also i don't think i am catching the Stale Element properly here. Any help would be greatly appreciated!`

pages_remaining = True

while pages_remaining:
    button=driver.find_element_by_class_name("arrow-right")
    href_data = button.get_attribute('href')
    if href_data is not None:
        soup=BeautifulSoup(driver.page_source,"html.parser")
        data = soup.find_all("div",{"class":"shelfProductStamp-content row"})
        count = 1
    for item in data:
            ProductText=item.find("a",attrs={"class":"shelfProductStamp-imageLink"})["title"]    
            if item.find("span",attrs={"class":"sf-pricedisplay"}) is not None:
                Price=item.find("span",attrs={"class":"sf-pricedisplay"}).text
            else:
                Price=""
            if item.find("p",attrs={"class":"sf-comparativeText"}) is not None:
                SubPrice1=item.find("p",attrs={"class":"sf-comparativeText"}).text
            else:
                SubPrice1=""
            if item.find("span",attrs={"class":"sf-regoption"}) is not None:
                Option=item.find("span",attrs={"class":"sf-regoption"}).text
            else:
                Option=""           
            SubPrice=str(SubPrice1)+"-"+str(Option)
            SaleDates=item.find("div",attrs={"class":"sale-dates"}).text
            urll2=driver.current_url
            PageNo=driver.find_element_by_class_name("current").text
            writer.writerow([ProductText,Price,SubPrice,SaleDates,PageNo])
            count+=1
    try:
        def find(driver):
            element = driver.find_element_by_class_name("arrow-right")
            if element:
                return element
            else:
                pages_remaining=False
                #driver.quit()
        time.sleep(10)
        driver.implicitly_wait(10)
        element = WebDriverWait(driver, 60).until(find)
        driver.execute_script("arguments[0].click();", element)
    except StaleElementReferenceException:
        pass
    else:
        break

Thanks


Solution

  • Thanks for your help here. I managed to fix this by simply adding another if statement at the end and swapping the time.sleep(10) as below

    try:
        def find(driver):
            element = driver.find_element_by_class_name("arrow-right")
            if element:
                return element                
        driver.implicitly_wait(10)
        element = WebDriverWait(driver, 60).until(find)
        driver.execute_script("arguments[0].click();", element)
        time.sleep(10)
    except StaleElementReferenceException:
        pass
    if href_data is None:
        break