LoginSignup
13

python + JupyterLab で Web スクレイピング

Last updated at Posted at 2020-10-22

はじめに

JupyterLab はお手軽に python を触ることができる実行環境です。

環境構築

git clone https://github.com/takiguchi-yu/python-jupyterLab.git
cd python-jupyterLab

JupyterLab 起動

docker-compose up -d

アクセス

初期画面

JupyterLab 終了

docker-compose down

Web スクレイピングサンプル

ちょっとした Web スクレイピングを書いてみる。
外部ファイルに記載されているURLを読み込んで、それを叩きながら結果を外部ファイルに出力するサンプル。
Webスクレイピング実装

from bs4 import BeautifulSoup
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1'
}
print('処理開始')
# URLのリスト(外部ファイル)を読み込む
with open('./input_urls.txt', mode='r', encoding='utf-8') as f:
    for url in f:
        result = requests.get(url.rstrip('\n'), headers=headers) # 注意:改行コードを取り除くこと
        print(result.status_code)
        soup = BeautifulSoup(result.content, 'html.parser')
        a = soup.find_all('ここにHTMLタグ名', {'class': 'ここにクラス名'})
        #a = soup.find_all('div', {'class': 'hoge-hoge'})  # 例
        b = a[0].find(text=True) # HTMLタグのテキストを取得
        # スクレイピング結果を外部ファイル(output.txt)に出力
        with open('./output.txt', 'a') as f:
            print(b, file=f)
print('処理完了')

ターミナルも使える

好きなライブラリを自由に入れることができる。

ターミナル1 ターミナル2

環境構築は以下を参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13