硒进入Python的无限循环

时间:2018-12-07 03:50:50

标签: python selenium while-loop infinite-loop

我正在尝试抓取一个网站,这是Python的新手。我设法拿出下面的代码。但是问题是它到达最后一页后进入无限循环,即Next按钮变灰了。 我也不认为我在这里正确地捕获了Stale元素。任何帮助将不胜感激!`

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

谢谢

2 个答案:

答案 0 :(得分:0)

pages_remaining = False函数中设置find()时,这是一个 local 变量。它与外部循环中的pages_remaining不同。

如果要那样做,则需要将其设置为全局。

答案 1 :(得分:0)

感谢您的帮助。我设法通过在末尾添加另一个if语句并按如下所示交换time.sleep(10)来解决此问题

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