LoginSignup
3
4

More than 3 years have passed since last update.

SPAで作成されたWebサイトをスクレイピングする方法

Posted at

Pythonでスクレイピングする方法としてこれまでrequestsモジュールを使っていたのですが、これはサーバ側で生成したHTMLを返すサイトでは使用できますが、JavaScriptを実行する前のレスポンスしか得られませんので、クライアント側でJavaScriptを実行してHTMLを手元で生成するようなSPAで作成されたサイトでは使えませんでした。

requests-htmlモジュール

SPAで作成されたサイトをスクレイピングするためにはrequests-htmlを使う必要があります。

インストール

pip install requests-html

使い方

main.py
# -*- coding: utf-8 -*-
import requests
from requests_html import HTMLSession

def main_render_javascript_page():
    url = 'https://hogehoge'
    session = HTMLSession()
    r = session.get(url)
    r.html.render()
    title =  r.html.find('body', first=True).text
    print(title)

def main_normal_page():
    url = 'https://hogehoge'
    r = requests.get(url)
    print(r.text)

if __name__ == '__main__':
    main_normal_page()
    main_render_javascript_page()

公式

参考サイト

https://dev.classmethod.jp/articles/python-asyncio/
https://blog.ikedaosushi.com/entry/2019/09/15/162445

3
4
0

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
3
4