PythonでHTMLテーブルデータをCSVに保存する方法
問題:
データ科学者にとって最も難しい課題の1つは、データを収集することです。実際のところ、ウェブにはたくさんのデータがあり、自動化によってデータを抽出しているだけです。
はじめに..
https://www.tutorialspoint.com/python/python_basic_operators.htmからHTMLテーブルに埋め込まれている基本的な操作データを抽出したかったのです。
うーん、データは多くのHTMLテーブルに散在しています。HTMLテーブルが1つしかない場合は、明らかに.csvファイルにコピーして貼り付けることができます。
ただし、1ページに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://www.tutorialspoint.com/python/python_dictionary.htmからHTMLテーブルを取得し、CSVファイルとして書き込みます。
最初のステップはインポートを行うことです。
import csv from urllib.request import urlopen from bs4 import BeautifulSoup url = 'https://www.tutorialspoint.com/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://www.tutorialspoint.com/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ページの表。
-
テキスト(TXT / CSV)ファイルをExcelファイルに変換する方法
テキストファイルにアイテムのリストがあり、テキストファイルからMicrosoftExcelにデータをインポートする場合 、手動で書き込むことなくそれを行うことができます。 Excelには、ユーザーが.txtファイルからスプレッドシートにすべてのテキストをインポートして、ユーザーがすばやく作業できるようにするオプションがあります。 メモ帳または.txtファイルに製品リストがあり、Excelスプレッドシートの列にそれらをインポートする必要があると仮定します。これを行うには2つの方法があります。まず、.txtファイルからすべてのテキストを手動でコピーして貼り付け、スプレッドシートに貼り付けることが
-
カンマを使用して Excel ファイルを CSV として保存する方法 (3 つの適切な方法)
コンマ区切り値 (CSV ) ファイルは、コンマで区切られたテキスト ファイルです。さまざまな種類のデータ分析中に役立ちます。 Excel を保存する必要がある場合があります。 CSV としてファイル さらに使用するためのファイル。この記事では Excel を保存する 3 つの適切な方法 CSV 形式のファイル 以下に添付されているワークブックをダウンロードして練習できます。 CSV とは CSV または コンマ区切り値 は、値をテキスト文字列として格納し、各値をコンマで区切る一般的なファイル形式です。 Pandas ライブラリなどのさまざまなソフトウェアおよびプログラミング言