Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Save Scrape Data Into CSV File?

I am so new in this Python, Selenium and BeautifulSoup. I already saw many tutorials online but I am so confused. Please help me. so basically this is my python code:

    from selenium import webdriver
    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 as bs
    
    #import requests
    import time 
    #import csv
    
    passwordStr = '***'
    usernameStr='***'
    
    chrome_path = r'C:\Users\wana isa\geckodriver-v0.26.0-win64\geckodriver.exe'
    browser = webdriver.Firefox(executable_path=r'C:\Users\wana isa\geckodriver-v0.26.0-win64\geckodriver.exe')
    browser.get(('http://*********/'))
    
    wait = WebDriverWait(browser,10)
    
    
    # wait for transition then continue to fill items
    #time.sleep(2)
    password = wait.until(EC.presence_of_element_located((By.ID, 'txt_Password')))
    password.send_keys(passwordStr)
    username = wait.until(EC.presence_of_element_located((By.ID, 'txt_Username')))
    username.send_keys(usernameStr)
    
    signInButton = browser.find_element_by_id('button')
    signInButton.click()
    browser.get(('http://******'))
    
    
    MainTab=browser.find_element_by_name('mainli_waninfo').click()
    SubTab=browser.find_element_by_name('subli_bssinfo').click()
    browser.switch_to.frame(browser.find_element_by_id('frameContent'))
    
    html=browser.page_source
    soup=bs(html,'lxml')
    #print(soup.prettify())
    
#for Service Proversioning Status , This is the data that i scrape and need to be saved into csv
    spsList=['ONT  Registration Status','OLT Service Configuration Status','EMS Configuration Status','ACS Registration Status']
    sps_id=['td1_2','td2_2','td3_2','td4_2']
    for i in range(len(sps_id)):
        elemntValu = browser.find_element_by_id(sps_id[i]).text
        output= print(spsList[i] + " : "+ elemntValu)
        
    browser.close()

this is the output:

enter image description here

i appreciate it so much if you can help me.

like image 926
Joojoo Avatar asked Feb 27 '26 11:02

Joojoo


1 Answers

add this import to your code :

import csv

add the following to your code :

  with open('FileName.csv', 'w', newline='') as file:
      writer = csv.writer(file)
      for i in range(len(sps_id)):
            elemntValu = browser.find_element_by_id(sps_id[i]).text
            output= print(spsList[i] + " : "+ elemntValu)
            writer.writerow([spsList[i], elemntValu])
  f.close()
  browser.close()
like image 94
Asmoun Avatar answered Mar 02 '26 00:03

Asmoun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!