簡體   English   中英

如何處理硒中的嵌套循環

[英]How to Handle Nested Loops in Selenium

我希望有人可以幫助我處理硒中的嵌套循環。 我正在嘗試使用硒抓取一個網站,碰巧我必須使用不同的鏈接抓取多個信息。

因此,我獲得了所有鏈接並遍歷了每個鏈接,但是在此過程中,第一個鏈接僅顯示了我需要的項目,然后代碼中斷了。

 def get_financial_info(self):

    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=1920x1080")
    driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/home/miracle/chromedriver')

    driver.get("https://www.financialjuice.com")

    try:
        WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='trendWrap']")))
    except TimeoutException:
        driver.quit()

    category_url = driver.find_elements_by_xpath("//ul[@class='nav navbar-nav']/li[@class='text-uppercase']/a[@href]")
    for record in category_url:
        driver.get(record.get_attribute("href"))
        news = {}
        title_element = driver.find_elements_by_xpath("//p[@class='headline-title']")

        for news_record in title_element:
            news['title'] = news_record.text

            print news

您的category_url僅在您定義了它的頁面上有效,並且在第一次重定向到另一個頁面后,它變得陳舊...

您需要更換

category_url = driver.find_elements_by_xpath("//ul[@class='nav navbar-nav']/li[@class='text-uppercase']/a[@href]")

category_url = [a.get_attribute("href") for a in driver.find_elements_by_xpath("//ul[@class='nav navbar-nav']/li[@class='text-uppercase']/a")]

然后遍歷鏈接列表為

for record in category_url:
    driver.get(record)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM