Python で Web スクレイピング

Photo by Clément H on Unsplash


Yahoo の USD/JPY の過去データを取り込むプログラムを作成中。
本日学んだことは以下の通り。
  1. Requests のインストール
  2. Beautifulsoup のインストール
  3. Webページの読み込み
  4. テーブルの探索とデータの取得
  5. 文字列の置き換え

■ソースコード
import gspread
import datetime
import csv
import requests
from bs4 import BeautifulSoup
# Web ページの読み込み
r = requests.get('https://info.finance.yahoo.co.jp/history/?code=usdjpy')
# コンテンツの解析
s = BeautifulSoup(r.content, "html.parser")
# テーブルの探索
tr = s.find_all('tr')
# テーブル内データの取得
for td in tr:
i = td.find_all('td')
for l in i:
if'<td>' in str(l):
lst = str(l)
# タグの消去
lst = lst.replace('<td>', '')
lst = lst.replace('</td>', '')
print(lst)
view raw gistfile1.txt hosted with ❤ by GitHub


Posted in  on 3/11/2020 by rteak |