Created
April 3, 2023 11:05
-
-
Save tango238/926358ea6827efebe12a978209674cc0 to your computer and use it in GitHub Desktop.
listed_companies
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 requests | |
from bs4 import BeautifulSoup | |
import csv | |
# 会社四季報の東証一部上場企業情報ページのURL | |
url = 'https://xxx.xxx/' | |
# HTTPリクエストを送信し、レスポンスを取得する | |
response = requests.get(url) | |
# BeautifulSoupを使ってHTMLをパースする | |
soup = BeautifulSoup(response.content, 'html.parser') | |
# CSVファイルに出力するヘッダー行を作成する | |
header = ['会社名', '所在地', '上場市場', '上場年月'] | |
# CSVファイルに出力するデータを格納するリストを作成する | |
data = [] | |
# 企業情報が格納されたテーブルを取得する | |
table = soup.find('table', class_='table01') | |
# テーブル内の全ての行を取得する | |
rows = table.find_all('tr') | |
# 各行のデータを取得し、dataリストに追加する | |
for row in rows[1:]: # 1行目はヘッダー行のためスキップ | |
cols = row.find_all('td') | |
name = cols[0].text.strip() # 企業名 | |
address = cols[1].text.strip() # 所在地 | |
market = cols[2].text.strip() # 上場市場 | |
date = cols[3].text.strip() # 上場年月 | |
data.append([name, address, market, date]) | |
# CSVファイルにデータを出力する | |
with open('listed_companies.csv', 'w', encoding='utf-8', newline='') as f: | |
writer = csv.writer(f) | |
writer.writerow(header) | |
writer.writerows(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment