Created
February 29, 2024 10:37
-
-
Save TomoG29/2270a7a2ff480491aedd746cb9d742e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import getpass | |
import csv | |
from bs4 import BeautifulSoup | |
# フォルダパス | |
html_track_dir = os.path.join(HTMLが保存されているフォルダ) | |
html_analysis_dir = os.path.join(解析結果を保存するフォルダ) | |
# 指定のクラス名とタグ名 | |
ANALYSIS_CLASS = '解析したいクラス' | |
TARGET_TAG = '解析したいタグ' | |
# HTML内の指定のクラス内にある指定のクラスとタグのデータを抽出する関数 | |
def extract_data(html_content): | |
data = [] # タイトルとURLのペアを保持するリスト | |
soup = BeautifulSoup(html_content, 'html.parser') | |
elements = soup.find_all(class_=ANALYSIS_CLASS) | |
for element in elements: | |
tags = element.find_all(TARGET_TAG) | |
for tag in tags: | |
title = tag.text.strip() | |
url = tag['href'] | |
data.append((title, url)) | |
return data | |
# CSVファイルに書き込む関数 | |
def write_to_csv(data): | |
if not data: | |
return # データが空の場合は何もしない | |
file_path = os.path.join(html_analysis_dir, 'analysis.csv') | |
with open(file_path, 'w', newline='', encoding='utf-8') as file: | |
writer = csv.writer(file) | |
for title, url in data: | |
writer.writerow([f"タイトル={title}", f"URL={url}"]) | |
writer.writerow([]) # 空行を挿入 | |
# メイン関数 | |
def main(): | |
extracted_data = [] # データを蓄積するリスト | |
# html_track_dirフォルダ内にある全てのファイルとフォルダを処理 | |
for root, dirs, files in os.walk(html_track_dir): | |
for filename in files: | |
if filename.endswith('.html'): | |
file_path = os.path.join(root, filename) | |
# ファイルをバイナリモードで開いてバイト列として読み取る | |
with open(file_path, 'rb') as file: | |
html_content = file.read() | |
# HTML内で特定の文字列を検索してURLを解析し、データを抽出しリストに追加 | |
extracted_data.extend(extract_data(html_content)) | |
# 全てのファイルの処理が終了した後に、CSVファイルに書き込む | |
write_to_csv(extracted_data) | |
print("プログラム終了") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment