我有一個固定的資料陣列結構,它在一個表中我用表保存了 html 現在我試圖把 html 檔案中的表放在一個 csv 檔案中來組織資料(用我看到的代碼在這里),我不斷收到錯誤訊息
這是代碼(取自本網站)
# Importing the required modules
import os
import sys
import pandas as pd
from bs4 import BeautifulSoup
path = 'file location' 'file.html'
# empty list
data = []
# for getting the header from
# the HTML file
list_header = []
soup = BeautifulSoup(open(path),'html.parser')
header = soup.find_all("table")[0].find("tr")
for items in header:
try:
list_header.append(items.get_text())
except:
continue
# for getting the data
HTML_data = soup.find_all("table")[0].find_all("tr")[1:]
for element in HTML_data:
sub_data = []
for sub_element in element:
try:
sub_data.append(sub_element.get_text())
except:
continue
data.append(sub_data)
# Storing the data into Pandas
# DataFrame
dataFrame = pd.DataFrame(data = data, columns = list_header)
# Converting Pandas DataFrame
# into CSV file
dataFrame.to_csv('Geeks.csv')
但得到這個錯誤
File, line 38, in <module>
dataFrame = pd.DataFrame(data = data, columns = list_header)
File, line 509, in __init__
arrays, columns = to_arrays(data, columns, dtype=dtype)
File, line 524, in to_arrays
return _list_to_arrays(data, columns, coerce_float=coerce_float, dtype=dtype)
File, line 567, in _list_to_arrays
raise ValueError(e) from e
ValueError: 1 columns passed, passed data had 7 columns
我究竟做錯了什么 ?
uj5u.com熱心網友回復:
我看到您的示例代碼中缺少的最重要的事情是您沒有迭代td每個行元素內的元素,也許該for sub_element in element行進行了單元格迭代,但尚不清楚。對于您自己和其他需要閱讀您的代碼的人(例如我們??),我建議您在查找和迭代元素時要非常明確。
我沒有安裝 BeautifulSoup (BS) 或 Pandas,但我想提供以下內容作為顯式遍歷表層次結構的模板。我正在使用 Python 的標準xml和csv模塊。(我認為 BS API 與 ElementTree 非常相似,可以指導您)
這是一個非常簡單的 HTML 表格,input.html:
<html>
<body>
<table>
<tr><td>Col1</td><td>Col2</td><td>Col3</td></tr>
<tr><td>Row1Col1</td><td>Row1Col2</td><td>Row1Col3</td></tr>
<tr><td>Row2Col1</td><td>Row2Col2</td><td>Row2Col3</td></tr>
<tr><td>Row3Col1</td><td>Row3Col2</td><td>Row3Col3</td></tr>
<tr><td>Row4Col1</td><td>Row4Col2</td><td>Row4Col3</td></tr>
</table>
</body>
</html>
import csv
from xml.etree import ElementTree as ET
# Accumulate rows from the table
all_rows = []
root = ET.parse('input.html')
# Get the table once
my_table = root.find('.//table')
# Iterate rows (tr) for that table
for elem_tr in my_table.findall('tr'):
new_row = []
# Iterate cells (td) per row
for elem_td in elem_tr.findall('td'):
# Build your row cell-by-cell
new_row.append(elem_td.text)
# Save finished row
all_rows.append(new_row)
# Finally write all rows
with open('out.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(all_rows)
當我運行它時,這是我的out.csv:
Col1,Col2,Col3
Row1Col1,Row1Col2,Row1Col3
Row2Col1,Row2Col2,Row2Col3
Row3Col1,Row3Col2,Row3Col3
Row4Col1,Row4Col2,Row4Col3
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397062.html
