user14241072
user14241072

Reputation:

how to export the Web scraping data into csv by python

i am web scraped the data by Beautifulsoup and printing the data. now i want the import to be imported to excel/csv my program below.i am new to python need help there are multiple pages that i have scraped now i need to export them to csv/excel

import requests
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from bs4 import BeautifulSoup as bs

def scrape_bid_data():

page_no = 1 #initial page number
while True:
    print('Hold on creating URL to fetch data...')
    URL = 'https://bidplus.gem.gov.in/bidlists?bidlists&page_no=' + str(page_no) #create dynamic URL
    print('URL cerated: ' + URL)

    scraped_data = requests.get(URL,verify=False) # request to get the data
    soup_data = bs(scraped_data.text, 'lxml') #parse the scraped data using lxml
    extracted_data = soup_data.find('div',{'id':'pagi_content'}) #find divs which contains required data

    if len(extracted_data) == 0: # **if block** which will check the length of extracted_data if it is 0 then quit and stop the further execution of script.
        break
    else:
        for idx in range(len(extracted_data)): # loops through all the divs and extract and print data
            if(idx % 2 == 1): #get data from odd indexes only because we have required data on odd indexes
                bid_data = extracted_data.contents[idx].text.strip().split('\n')
                print('-' * 100)
                print(bid_data[0]) #BID number
                print(bid_data[5]) #Items
                print(bid_data[6]) #Quantitiy Required
                print(bid_data[10] + bid_data[12].strip()) #Department name and address
                print(bid_data[16]) #Start date
                print(bid_data[17]) #End date                   
                print('-' * 100)

        page_no +=1 #increments the page number by 1

 scrape_bid_data()

data is coming in the form like this below:enter image description here

Upvotes: 2

Views: 650

Answers (1)

Anuj Jindal
Anuj Jindal

Reputation: 65

You can use pandas

pip install pandas

obj can be

bid_data = []
for obj in list:
    obj= {
        "bid_data_0" :bid_data[0],
        "bid_data_5" :bid_data[5],
        "bid_data_6" :bid_data[6],
        "bid_data_10" :bid_data[10],
        "bid_data_12" :bid_data[12].strip(),
        "bid_data_17" :bid_data_17,
    }
bid_data.append(obj)

you can format bid_data to dict obj and in that object add only required field

import pandas as pd

bid_data = pd.DataFrame(bid_data)
bid_data.to_csv("file_name.csv", index=True, encoding='utf-8')

it is the simplest method I have ever used for exporting data to csv. Let me know if encounter any problem

Upvotes: 1

Related Questions