While循环在第一次迭代时跳过?

时间:2020-05-11 07:32:50

标签: python selenium web-scraping while-loop

我正在尝试编写此while循环,该循环自动按首页上的下一个按钮,但是在遵守我在while:else:部分中设置的条件之后。如何自动执行无条件的第一次单击,因为现在它会按照else:条件自动关闭。

有关更多上下文,my_url是运动鞋网站的首页。 共有34个鞋子页面需要进行浏览,但是我没有尝试按页面编号进行浏览,而是尝试将页面进行浏览以使其适应其他用途。当它到达最后一页并单击下一步按钮时,它返回到第1页。这就是为什么我将else语句设置为在返回my_url时退出。

#Once done scraping page, clicks next page button until it returns to page 1
    def next_page(self, driver):
        next_button = driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[3]/div/div[2]/ul/li[3]/button')
        next_button.click()
        driver.implicitly_wait(10)
        while driver.current_url != my_url:
            next_button = driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[3]/div/div[2]/ul/li[3]/button')
            driver.implicitly_wait(15)
            #run sneakers program again
            #scraper.main_page(driver)
            #scraper.x_path_creator(driver)
            #scraper.shoe_page_scrape(driver)
            scraper.next_page(driver)


            else:
                print("Scraping for this shoe is done.")
                driver.quit()

1 个答案:

答案 0 :(得分:1)

另一个选择是将其转换为“ do ... while”循环,以便始终执行第一次迭代,并在循环的末尾而不是开始检查结束条件。

Python没有“内置” do ... while循环,通常的方法是:

while True:
   <insert code here>
   if <condition>:
      break

或其某些变体。请注意,由于这里的条件是 exit 条件,因此它与while的条件相反,因此您将拥有

        while True:
            next_button = driver.find_element_by_xpath('/html/body/div/div[2]/div[1]/div[3]/div/div[2]/ul/li[3]/button')
            driver.implicitly_wait(15)
            scraper.next_page(driver)

            # stop if back at first page
            if driver.current_url == my_url:
                break

您的else子句似乎也没有用:Python的<loop>: else:构造有点奇怪,但其要点是区分“正常终止”和显式终止(通过break):else子句仅在正常终止的情况下执行。

不仅您没有在代码中使用break,即使您可能想终止驱动程序(也可能不是,因为驱动程序并不真正属于该功能,所以似乎很冒险)

相关问题