Webページ内に記載されているリンク先の名称とURLを抽出して一覧にする方法
Python+BeautifulSoup
やりたいこと
験潮場一覧表|海岸昇降検知センター
https://cais.gsi.go.jp/cmdc/center/itiran.html
から各験潮場名称と験潮場へのリンク先URLをExcelにまとめたい
pythonコードの作成と実行
href-text-get.py ファイルを作成
import requests
from bs4 import BeautifulSoup
import urllib.parse
# アクセスするURL
url = "https://cais.gsi.go.jp/cmdc/center/itiran.html"
# HTMLソースを得る
r = requests.get(url)
# BeautifulSoupで解析
soup = BeautifulSoup(r.content, 'html.parser')
# a_tags = soup.find_all("a") # aタグを全て取得
a_tags = soup.css.select('table a') # tableタグ内のaタグを全て取得 cssセレクタを使用
for a_tag in a_tags:
href = a_tag.get('href')
href_abs= urllib.parse.urljoin(url, href) #相対URLを絶対URLに変換
text = a_tag.text
print(text, ",",href_abs)
験潮場の名称とURLはtableタグ内のaタグで囲まれている
例:
<table summary="国土地理院験潮場">
<a href="kenchojo/oshoro/oshoro.html">忍路</a>
</table>
リダイレクトでファイル(result.txt)に保存
python href-text-get.py > result.txt
保存したファイルをExcelに取り込む
result.txtの内容
忍路 , https://cais.gsi.go.jp/cmdc/center/kenchojo/oshoro/oshoro.html
浅虫 , https://cais.gsi.go.jp/cmdc/center/kenchojo/asamushi/asamushi.html
男鹿 , https://cais.gsi.go.jp/cmdc/center/kenchojo/oga/oga.html
鼠ケ関 , https://cais.gsi.go.jp/cmdc/center/kenchojo/nezugaseki/nezugaseki.html
相馬 , https://cais.gsi.go.jp/cmdc/center/kenchojo/soma/soma.html
小木 , https://cais.gsi.go.jp/cmdc/center/kenchojo/ogi/ogi.html
柏崎 , https://cais.gsi.go.jp/cmdc/center/kenchojo/kashiwazaki/kashiwazaki.html
勝浦 , https://cais.gsi.go.jp/cmdc/center/kenchojo/katsuura/katsuura.html
油壺 , https://cais.gsi.go.jp/cmdc/center/kenchojo/aburatsubo/aburatsubo.html
<SKIP>
csvファイルになっているresult.txtをExcelで取り込む