You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium嵌套循环问题:无法输入第二个from_date值

Fixing Your Selenium Date Input & Loop Logic Issue

First, let's break down the core problems in your code that are causing the stuck inner loop and input failures:

  • Incorrect loop structure: You’re using three nested loops, but date_from and date_to are paired (each start date matches an end date). Nesting them creates every possible combination of dates, which isn’t your intended behavior—and this is why you’re getting stuck in the inner loop.
  • Missing explicit waits: After clicking buttons or interacting with the page, elements might not be immediately ready for input. Without waiting, Selenium can try to interact with elements that aren’t fully loaded yet.
  • Stale dropdown element: You initialize the Select object once at the start, but after page interactions, this element might become "stale" (no longer attached to the DOM). You need to re-locate it each time you select a new index.
  • No validation of element state: Clearing inputs doesn’t guarantee the field is ready to accept new text—you should wait for the input to be interactable before sending keys.

Here's the revised, working code with fixes for all these issues:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

browser = webdriver.Firefox()
# Pair start and end dates together for proper matching
date_pairs = [
    ('02-01-2000', '31-12-2000'),
    ('02-01-2001', '31-12-2001'),
    ('02-01-2002', '31-12-2002'),
    ('02-01-2003', '31-12-2003'),
    ('02-01-2004', '31-12-2004'),
    ('02-01-2005', '31-12-2005'),
    ('02-01-2006', '31-12-2006'),
    ('02-01-2007', '31-12-2007'),
    ('02-01-2008', '31-12-2008'),
    ('02-01-2009', '31-12-2009'),
    ('02-01-2010', '31-12-2010'),
    ('02-01-2011', '31-12-2011'),
    ('02-01-2012', '31-12-2012'),
    ('02-01-2013', '31-12-2013'),
    ('02-01-2014', '31-12-2014'),
    ('02-01-2015', '31-12-2015'),
    ('02-01-2016', '31-12-2016'),
    ('02-01-2017', '31-12-2017')
]
browser.get('https://www.nseindia.com/products/content/equities/indices/historical_pepb.htm')
indices = ['NIFTY 50', 'NIFTY Next 50', 'NIFTY Auto', 'NIFTY Bank', 'NIFTY Energy', 'NIFTY Financial Services', 'NIFTY FMCG', 'NIFTY IT', 'NIFTY Media', 'NIFTY Metal', 'NIFTY Pharma', 'NIFTY Private Bank', 'NIFTY PSU Bank', 'NIFTY Realty']

# Wait for the yield button to be clickable before interacting
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#yield4'))).click()

for index in indices:
    # Re-locate the dropdown each time to avoid stale element errors
    select = Select(WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="IndexName"]'))))
    select.select_by_visible_text(index)
    
    for from_date, to_date in date_pairs:
        # Wait for fromDate input to be ready, clear it, then send keys
        from_input = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#fromDate')))
        from_input.clear()
        from_input.send_keys(from_date)
        
        # Repeat for toDate input
        to_input = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#toDate')))
        to_input.clear()
        to_input.send_keys(to_date)
        
        # Click "Get Data" and wait for results to load
        WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#get'))).click()
        # Wait for the download link to become available
        download_link = WebDriverWait(browser, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a.historical-csv-downld')))
        # Scroll directly to the download link (more reliable than scrolling to page bottom)
        browser.execute_script("arguments[0].scrollIntoView();", download_link)
        download_link.click()
        
        # Add a small delay to let the download start before next iteration (adjust as needed)
        time.sleep(2)

browser.quit()

Key improvements made:

  • Used paired date tuples to loop through matching start/end dates instead of nested loops
  • Added explicit waits for all interactive elements to ensure they’re ready before interaction
  • Re-locate the dropdown element in each index loop to prevent stale element exceptions
  • Used scrollIntoView() to directly scroll to the download link instead of scrolling to the page bottom
  • Added a small delay after clicking download to ensure the file starts downloading before moving on

内容的提问来源于stack exchange,提问作者Ted

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:26:48