AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79574809
Accepted
chintan patel
chintan patel
Asked: 2025-04-15 17:32:16 +0800 CST2025-04-15 17:32:16 +0800 CST 2025-04-15 17:32:16 +0800 CST

Enfrentando um erro ao percorrer a lista e salvar os dados

  • 772

Estou tentando acessar dados de cerca de 500 ações do "https://www.nseindia.com/report-detail/eq_security" para os quais mencionei as etapas.

  1. Abra a URL
  2. insira o símbolo da ação e clique na primeira opção do menu suspenso.
  3. Clique em 1W para abrir os dados semanais.
  4. Da tabela, extraia dados de uma data específica para Quantidade Total Negociada, Nº de Negociações, Qtd. Entregável e % Qtd Diária para Qtd. Negociada.
  5. Salve esses dados em um arquivo CSV.

Então meu arquivo CSV conterá 5 colunas e cerca de 500 linhas, como abaixo. insira a descrição da imagem aqui

Criei o código abaixo, mas esses são os problemas que estou enfrentando.

  1. Ele está abrindo o Chrome novamente para cada símbolo, tentei apagar o símbolo anterior e inserir um novo, mas não está funcionando. Portanto, ele está coletando os mesmos dados para todas as ações
  2. Não tenho dados históricos, então, se eu quiser ter dados de 3 meses para cada ação, preciso clicar em "3M" para coletar todos os dados. Mas não sei como fazer isso? Por favor, compartilhe este código separadamente.

Atualizarei a lista para incluir todas as ações e farei isso diariamente, então só preciso alterar a data no código no futuro.

Abaixo está o código que tenho:

import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import time
import csv
import os

# Step 1: Create a list of stock symbols (for illustration purposes, here are a few)
# You can replace this with a list of 500 stock symbols
stock_symbols = ["INFY", "TCS", "RELIANCE", "HDFCBANK", "ITC"]  # Add all 500 symbols here

# Define the CSV file name
csv_file = "nse_data.csv"

# Check if file already exists (to avoid writing headers again)
file_exists = os.path.isfile(csv_file)

# Step 2: Open browser and go to URL
driver = uc.Chrome()
driver.get("https://www.nseindia.com/report-detail/eq_security")
driver.maximize_window()
wait = WebDriverWait(driver, 10)

# Function to get data for a single stock
def get_stock_data(symbol):
    # Step 1: Clear the symbol input field and enter new symbol
    symbol_input = wait.until(EC.element_to_be_clickable((By.ID, "hsa-symbol")))

    # Clear the input field by sending backspace
    symbol_input.click()
    symbol_input.clear()  # Clear the previous symbol
    
    # Wait a moment to ensure the field is cleared before entering the new symbol
    time.sleep(0.5)  # Add a small delay for clarity

    # Enter the new symbol
    symbol_input.send_keys(symbol)  # Enter the new symbol
    print(f"✅ Selected symbol '{symbol}'")
    time.sleep(2)

    # Step 2: Click on the first dropdown option
    wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@id='hsa-symbol_listbox']//div//div[1]"))).click()
    print(f"✅ Clicked on the first option for '{symbol}'")
    time.sleep(5)

    # Step 3: Click on the 1W button
    one_week_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="oneW"]')))
    one_week_button.click()
    print(f"✅ Clicked on the 1W button for {symbol}")
    time.sleep(5)

    # Step 4: Parse the table and extract data for a specific date
    target_date = "11-Apr-2025"
    soup = BeautifulSoup(driver.page_source, "html.parser")

    table = soup.find("table", {"id": "hsaTable"})
    rows = table.find_all("tr")

    # Get headers to map column names to index
    headers = [th.text.strip() for th in rows[0].find_all("th")]

    # Mapping the column names we care about
    columns_of_interest = ["Date", "Total Traded Quantity", "No. of Trades", "Deliverable Qty", "% Dly Qt to Traded Qty"]
    indices = {col: headers.index(col) for col in columns_of_interest}

    # Look for the row with the target date
    for row in rows[1:]:
        cols = [td.text.strip() for td in row.find_all("td")]
        if cols and cols[indices["Date"]] == target_date:
            extracted_data = {
                "Symbol": symbol,
                "Date": cols[indices["Date"]],
                "Total Traded Quantity": cols[indices["Total Traded Quantity"]],
                "No. of Trades": cols[indices["No. of Trades"]],
                "Deliverable Qty": cols[indices["Deliverable Qty"]],
                "% Dly Qt to Traded Qty": cols[indices["% Dly Qt to Traded Qty"]],
            }
            print(f"✅ Data for {symbol} on {target_date}:")
            for key, val in extracted_data.items():
                print(f"{key}: {val}")
            break
    else:
        print(f"❌ No data found for date: {target_date} for {symbol}")
        extracted_data = None

    return extracted_data

# Write data for multiple stocks
for symbol in stock_symbols:
    extracted_data = get_stock_data(symbol)
    
    if extracted_data:
        # Write to CSV
        with open(csv_file, mode="a", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=extracted_data.keys())

            # Write header only once
            if not file_exists:
                writer.writeheader()

            # Write the row
            writer.writerow(extracted_data)

        print(f"✅ Data for {symbol} written to CSV.")

# Close the browser when all data is collected
driver.quit()

print("✅ All data extraction completed.")
python
  • 1 1 respostas
  • 46 Views

1 respostas

  • Voted
  1. Best Answer
    Shawn
    2025-04-15T18:41:31+08:002025-04-15T18:41:31+08:00

    Em relação à sua primeira pergunta, você precisa se certificar de que o valor no campo de entrada esteja limpo antes de inserir o próximo símbolo. Use o código abaixo para fazer isso.

    def clear_web_field(element):
        while element.get_attribute("value") != "":
            element.send_keys(Keys.BACKSPACE)
    

    Código completo:

    import undetected_chromedriver as uc
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys
    from bs4 import BeautifulSoup
    import time
    import csv
    import os
    
    # Step 1: Create a list of stock symbols (for illustration purposes, here are a few)
    # You can replace this with a list of 500 stock symbols
    stock_symbols = ["INFY", "TCS", "RELIANCE", "HDFCBANK", "ITC"]  # Add all 500 symbols here
    
    # Define the CSV file name
    csv_file = "nse_data.csv"
    
    # Check if file already exists (to avoid writing headers again)
    file_exists = os.path.isfile(csv_file)
    
    # Step 2: Open browser and go to URL
    driver = uc.Chrome()
    driver.get("https://www.nseindia.com/report-detail/eq_security")
    driver.maximize_window()
    wait = WebDriverWait(driver, 10)
    
    def clear_web_field(element):
        while element.get_attribute("value") != "":
            element.send_keys(Keys.BACKSPACE)
    
    # Function to get data for a single stock
    def get_stock_data(symbol):
        # Step 1: Clear the symbol input field and enter new symbol
        symbol_input = wait.until(EC.element_to_be_clickable((By.ID, "hsa-symbol")))
    
        # Clear the input field by sending backspace
        clear_web_field(symbol_input)
    
        # Wait a moment to ensure the field is cleared before entering the new symbol
        time.sleep(0.5)  # Add a small delay for clarity
    
        # Enter the new symbol
        symbol_input.send_keys(symbol)  # Enter the new symbol
        print(f"✅ Selected symbol '{symbol}'")
        time.sleep(2)
    
        # Step 2: Click on the first dropdown option
        wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@id='hsa-symbol_listbox']//div//div[1]"))).click()
        print(f"✅ Clicked on the first option for '{symbol}'")
        time.sleep(5)
    
        # Step 3: Click on the 1W button
        one_week_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="oneW"]')))
        one_week_button.click()
        print(f"✅ Clicked on the 1W button for {symbol}")
        time.sleep(5)
    
        # Step 4: Parse the table and extract data for a specific date
        target_date = "11-Apr-2025"
        soup = BeautifulSoup(driver.page_source, "html.parser")
    
        table = soup.find("table", {"id": "hsaTable"})
        rows = table.find_all("tr")
    
        # Get headers to map column names to index
        headers = [th.text.strip() for th in rows[0].find_all("th")]
    
        # Mapping the column names we care about
        columns_of_interest = ["Date", "Total Traded Quantity", "No. of Trades", "Deliverable Qty",
                               "% Dly Qt to Traded Qty"]
        indices = {col: headers.index(col) for col in columns_of_interest}
    
        # Look for the row with the target date
        for row in rows[1:]:
            cols = [td.text.strip() for td in row.find_all("td")]
            if cols and cols[indices["Date"]] == target_date:
                extracted_data = {
                    "Symbol": symbol,
                    "Date": cols[indices["Date"]],
                    "Total Traded Quantity": cols[indices["Total Traded Quantity"]],
                    "No. of Trades": cols[indices["No. of Trades"]],
                    "Deliverable Qty": cols[indices["Deliverable Qty"]],
                    "% Dly Qt to Traded Qty": cols[indices["% Dly Qt to Traded Qty"]],
                }
                print(f"✅ Data for {symbol} on {target_date}:")
                for key, val in extracted_data.items():
                    print(f"{key}: {val}")
                break
        else:
            print(f"❌ No data found for date: {target_date} for {symbol}")
            extracted_data = None
    
        return extracted_data
    
    
    # Write data for multiple stocks
    for symbol in stock_symbols:
        extracted_data = get_stock_data(symbol)
    
        if extracted_data:
            # Write to CSV
            with open(csv_file, mode="a", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=extracted_data.keys())
    
                # Write header only once
                if not file_exists:
                    writer.writeheader()
    
                # Write the row
                writer.writerow(extracted_data)
    
            print(f"✅ Data for {symbol} written to CSV.")
    
    # Close the browser when all data is collected
    driver.quit()
    
    print("✅ All data extraction completed.")
    

    SEGUNDA PERGUNTA: Não tenho certeza se é isso que você está procurando. Veja o código abaixo para clicar em3M

    # Using ID locator (this is preferred)
    three_month_button = wait.until(EC.element_to_be_clickable((By.ID, 'threeM')))
    three_month_button.click()
    
    #or using the XPath expression
    three_month_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//a[@id="threeM"]')))
    three_month_button.click()
    

    ATUALIZAÇÃO - Resposta à segunda pergunta:

    Verifique o código abaixo. Removi a lógica da data-alvo (11 de abril). O código abaixo buscará dados da 3M e os gravará em um arquivo CSV.
    import undetected_chromedriver as uc
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.keys import Keys
    from bs4 import BeautifulSoup
    import time
    import csv
    import os
    
    # Step 1: Create a list of stock symbols (for illustration purposes, here are a few)
    # You can replace this with a list of 500 stock symbols
    stock_symbols = ["INFY", "TCS", "RELIANCE", "HDFCBANK", "ITC"]  # Add all 500 symbols here
    
    # Define the CSV file name
    csv_file = "nse_data.csv"
    
    # Check if file already exists (to avoid writing headers again)
    file_exists = os.path.isfile(csv_file)
    header_written = os.path.getsize(csv_file) > 0 if file_exists else False  # Track header writing during script run
    
    # Step 2: Open browser and go to URL
    driver = uc.Chrome()
    driver.get("https://www.nseindia.com/report-detail/eq_security")
    driver.maximize_window()
    wait = WebDriverWait(driver, 10)
    
    def clear_web_field(element):
        while element.get_attribute("value") != "":
            element.send_keys(Keys.BACKSPACE)
    
    # Function to get data for a single stock
    def get_stock_data(symbol):
        # Step 1: Clear the symbol input field and enter new symbol
        symbol_input = wait.until(EC.element_to_be_clickable((By.ID, "hsa-symbol")))
    
        # Clear the input field by sending backspace
        clear_web_field(symbol_input)
    
        # Wait a moment to ensure the field is cleared before entering the new symbol
        time.sleep(0.5)  # Add a small delay for clarity
    
        # Enter the new symbol
        symbol_input.send_keys(symbol)  # Enter the new symbol
        print(f"✅ Selected symbol '{symbol}'")
        time.sleep(2)
    
        # Step 2: Click on the first dropdown option
        wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@id='hsa-symbol_listbox']//div//div[1]"))).click()
        print(f"✅ Clicked on the first option for '{symbol}'")
        time.sleep(5)
    
        # Step 3: Click on the 1W button
        one_week_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="threeM"]')))
        one_week_button.click()
    
        print(f"✅ Clicked on the 1W button for {symbol}")
        time.sleep(5)
    
        # Step 4: Parse the table and extract data for a specific date
        target_date = "11-Apr-2025"
        soup = BeautifulSoup(driver.page_source, "html.parser")
    
        table = soup.find("table", {"id": "hsaTable"})
        rows = table.find_all("tr")
    
        # Get headers to map column names to index
        headers = [th.text.strip() for th in rows[0].find_all("th")]
    
        # Mapping the column names we care about
        columns_of_interest = ["Date", "Total Traded Quantity", "No. of Trades", "Deliverable Qty",
                               "% Dly Qt to Traded Qty"]
        indices = {col: headers.index(col) for col in columns_of_interest}
    
        extracted_data_list = []
    
        for row in rows[1:]:
            cols = [td.text.strip() for td in row.find_all("td")]
            extracted_data = {
                "Symbol": symbol,
                "Date": cols[indices["Date"]],
                "Total Traded Quantity": cols[indices["Total Traded Quantity"]],
                "No. of Trades": cols[indices["No. of Trades"]],
                "Deliverable Qty": cols[indices["Deliverable Qty"]],
                "% Dly Qt to Traded Qty": cols[indices["% Dly Qt to Traded Qty"]],
            }
            extracted_data_list.append(extracted_data)
            print(f"✅ Data for {symbol} on {target_date}:")
            for key, val in extracted_data.items():
                print(f"{key}: {val}")
        return extracted_data_list
    
    
    # Write data for multiple stocks
    for symbol in stock_symbols:
        extracted_data_list  = get_stock_data(symbol)
    
        if extracted_data_list:
            # Write to CSV
            with open(csv_file, mode="a", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=extracted_data_list[0].keys())
    
                # Write header only once
                if not header_written:
                    writer.writeheader()
                    header_written = True
    
                # Write the row
                for row_data in extracted_data_list:
                    writer.writerow(row_data)
    
            print(f"✅ Data for {symbol} written to CSV.")
    
    # Close the browser when all data is collected
    driver.quit()
    
    print("✅ All data extraction completed.")
    
    • 1

relate perguntas

  • Como divido o loop for em 3 quadros de dados individuais?

  • Como verificar se todas as colunas flutuantes em um Pandas DataFrame são aproximadamente iguais ou próximas

  • Como funciona o "load_dataset", já que não está detectando arquivos de exemplo?

  • Por que a comparação de string pandas.eval() retorna False

  • Python tkinter/ ttkboostrap dateentry não funciona quando no estado somente leitura

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve