如何在Python中將HTML表格資料儲存到CSV
問題
對於資料科學家來說,收集資料是最具挑戰性的任務之一。事實上,網路上有很多資料可用,只是需要透過自動化來提取這些資料。
簡介…
我想從https://tutorialspoint.tw/python/python_basic_operators.htm中提取嵌入在HTML表格中的基本操作資料。
嗯,資料分散在許多HTML表格中,如果只有一個HTML表格,我顯然可以使用複製貼上到.csv檔案。
但是,如果一個頁面中有超過5個表格,那顯然很痛苦。不是嗎?
怎麼做…
1. 如果你想建立一個csv檔案,我會快速向你展示如何輕鬆地建立一個csv檔案。
import csv # Open File in Write mode , if not found it will create one File = open('test.csv', 'w+') Data = csv.writer(File) # My Header Data.writerow(('Column1', 'Column2', 'Column3')) # Write data for i in range(20): Data.writerow((i, i+1, i+2)) # close my file File.close()
輸出
執行上述程式碼後,將在與程式碼相同的目錄中生成一個test.csv檔案。
2. 現在讓我們從https://tutorialspoint.tw/python/python_dictionary.htm檢索HTML表格並將其寫入CSV檔案。
第一步是匯入。
import csv from urllib.request import urlopen from bs4 import BeautifulSoup url = 'https://tutorialspoint.tw/python/python_dictionary.htm'
開啟HTML檔案,並使用urlopen將其儲存在html物件中。
輸出
html = urlopen(url) soup = BeautifulSoup(html, 'html.parser')
查詢html表格內的表格,讓我們提取表格資料。為了演示,我將只提取第一個表格[0]。
輸出
table = soup.find_all('table')[0] rows = table.find_all('tr')
輸出
print(rows)
輸出
[<tr> <th style='text-align:center;width:5%'>Sr.No.</th> <th style='text-align:center;width:95%'>Function with Description</th> </tr>, <tr> <td class='ts'>1</td> <td><a href='/python/dictionary_cmp.htm'>cmp(dict1, dict2)</a> <p>Compares elements of both dict.</p></td> </tr>, <tr> <td class='ts'>2</td> <td><a href='/python/dictionary_len.htm'>len(dict)</a> <p>Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.</p></td> </tr>, <tr> <td class='ts'>3</td> <td><a href='/python/dictionary_str.htm'>str(dict)</a> <p>Produces a printable string representation of a dictionary</p></td> </tr>, <tr> <td class='ts'>4</td> <td><a href='/python/dictionary_type.htm'>type(variable)</a> <p>Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.</p></td> </tr>]
5. 現在我們將資料寫入csv檔案。
示例
File = open('my_html_data_to_csv.csv', 'wt+') Data = csv.writer(File) try: for row in rows: FilteredRow = [] for cell in row.find_all(['td', 'th']): FilteredRow.append(cell.get_text()) Data.writerow(FilteredRow) finally: File.close()
6. 結果現在已儲存到my_html_data_to_csv.csv檔案中。
示例
我們將把上面解釋的所有內容放在一起。
示例
import csv from urllib.request import urlopen from bs4 import BeautifulSoup # set the url.. url = 'https://tutorialspoint.tw/python/python_basic_syntax.htm' # Open the url and parse the html html = urlopen(url) soup = BeautifulSoup(html, 'html.parser') # extract the first table table = soup.find_all('table')[0] rows = table.find_all('tr') # write the content to the file File = open('my_html_data_to_csv.csv', 'wt+') Data = csv.writer(File) try: for row in rows: FilteredRow = [] for cell in row.find_all(['td', 'th']): FilteredRow.append(cell.get_text()) Data.writerow(FilteredRow) finally: File.close()
html頁面中的表格。
廣告