簡體   English   中英

如何沿 CSV 文件中的列寫入數據?

[英]How do I write my data along the columns in a CSV file?

當我寫入 csv 文件時,我的所有數據僅打印在第一列中。 使用我的循環,我如何遍歷列來寫入數據?

import csv
import bs4
import urllib
from urllib.request import  urlopen as uReq
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as soup

#For sites that can't be opened due to Urllib blocker, use a Mozilla User agent to get access
pageRequest = Request('https://coronavirusbellcurve.com/', headers = {'User-Agent': 'Mozilla/5.0'})
htmlPage = urlopen(pageRequest).read()
page_soup = soup(htmlPage, 'html.parser')
specificDiv = page_soup.find("div", {"class": "table-responsive-xl"})

TbodyStats = specificDiv.table.tbody.tr.contents
TbodyDates = specificDiv.table.thead.tr.contents


with open('CovidHTML.csv','w', newline= '') as file:
    theWriter = csv.writer(file)             
    theWriter.writerow(['5/4', ' 5/5', ' 5/6',' 5/7',' 5/8',' 5/9'])
    for i in range(3,len(TbodyStats)):
        if i%2 != 0:
            theWriter.writerow([TbodyStats[i].text])

另一種方法,僅供參考。

from simplified_scrapy import SimplifiedDoc,utils,req
html = req.get('https://coronavirusbellcurve.com/')
doc = SimplifiedDoc(html)
specificDiv = doc.select('div.table-responsive-xl') # Get first div. If you want to get all divs, use this method: doc.selects('div.table-responsive-xl')
# TbodyStats = specificDiv.tbody.trs.selects('td|th').text # Get data
# TbodyDates = specificDiv.thead.trs.selects('td|th').text # Get date
data = specificDiv.table.trs.selects('td|th').text # Get all
rows = []
for row in data:
    rows.append(row[1:])
utils.save2csv('test.csv',rows)

結果:

5/5,5/6,5/7,5/8,5/9
1213260,1237960,1266822,1294664,1314610
24423,24700,28862,27842,19946
2.05%,2.04%,2.33%,2.20%,1.54%

我認為您可以做到這一點(我無法確定測試,因為我手頭沒有您的確切數據):

row = []
for i in range(3, len(TbodyStats), 2):
    row.append(TbodyStats[i].text)
    if len(row) == 6:
        theWriter.writerow(row)
        row = []

我將“步驟”添加到您的范圍內,因此您不必使用 % 來查找奇數索引,然后只構建每一行直到它達到 6 個成員,然后將其刷新到 csv 文件,然后清空該行以便您可以重復這個過程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM