如何通过python将多页数据导出到excel中?

Posted

技术标签:

【中文标题】如何通过python将多页数据导出到excel中?【英文标题】:how to export the multiple pages data into excel by python? 【发布时间】:2020-12-26 08:59:16 【问题描述】:

下面是我的程序,我在控制台中使用 beautifulsoup 打印数据,但我想导出到带有预定义标题的 excel/csv,并且我正在 抓取大量页面(850) 每行包含5行数据>Python新手需要帮助

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()

【问题讨论】:

这看起来不像是beautifulsoup 问题,而是“如何将这些数据导出到电子表格中?”。如果是这种情况,那么我建议寻找像 pyexcel 这样的处理 .xls 和 .csv 文件的库。 我知道请帮助我是 python 新手 【参考方案1】:
import requests
from urllib3.exceptions import InsecureRequestWarning
import csv

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

f = csv.writer(open('gembid.csv', 'w'))
f.writerow(['Bidnumber', 'Items', 'Quantitiy', 'Department', 'Enddate'])


def scrape_bid_data():
    page_no = 1
    while page_no < 911:
        print('Hold on creating URL to fetch data...')
        url = 'https://bidplus.gem.gov.in/bidlists?bidlists&page_no=' + str(page_no)
        print('URL created: ' + url)
        scraped_data = requests.get(url, verify=False)
        soup_data = bs(scraped_data.text, 'lxml')
        extracted_data = soup_data.find('div', 'id': 'pagi_content')
        if len(extracted_data) == 0:
            break
        else:
            for idx in range(len(extracted_data)):
                if (idx % 2 == 1):
                    bid_data = extracted_data.contents[idx].text.strip().split('\n')

                    bidno = bid_data[0].split(":")[-1]
                    items = bid_data[5].split(":")[-1]
                    qnty = int(bid_data[6].split(':')[1].strip())
                    dept = (bid_data[10] + bid_data[12].strip()).split(":")[-1]
                    edate = bid_data[17].split("End Date:")[-1]
                    f.writerow([bidno, items, qnty, dept, edate])

            page_no=page_no+1
scrape_bid_data()

【讨论】:

@balmy 你能告诉我如何检查我是否要检查 bid_data[8] 长度是否 >0 然后代码执行否则不

以上是关于如何通过python将多页数据导出到excel中?的主要内容,如果未能解决你的问题,请参考以下文章

多页Excel转换成PDF时如何保存为单独文件

使用python将多页pdf文件拆分为多个pdf文件?

如何在报表打印时,将多页合为一页

OBIEE 11 - 如何在没有提示的情况下在 excel 中导出多页仪表板

如何将MYSQL中数据导出到EXCEL表中 python 脚本?

如何使用python将大量数据导出到Excel中的小技巧