Python: Requests-HTML の使い方

Requests-HTML は、Web スクレイピングを簡単に操作にするモジュールである。HTML のパースなどページを取り出して目的の要素を処理する。
エンジニア速報は Twitter の@commteで配信しています。
Requests-HTML の作者である Kenneth Reitz 氏 は、HTTP クライアントインターフェースとして広く使われている Requests モジュールの作者でもある。設計はクリーンだ。
Requests-HTML は、ページに含まれているすべてのリンクやコンテンツ全体の他、HTML 要素の属性を知ることができる。
作者の github psf/requests-htmlによると、次の情報を得ることができると書かれている。
- JavaScript サポート
- CSS セレクター
- XPath セレクター
- 模擬ユーザーエージェント
- リダイレクトの自動フォロー
- 接続プール
- Cookie の永続性
- 非同期サポート
インストール コマンド
pipenv install requests-html
colab にはプリインストールされていない。colab 上でインストールする場合は次のコマンドをコードセルに入力する。
!pip install requests-html
CSS セレクタを見つける
ターゲットのスクレイピング先に記述された html ソースコードがこちらだったとする。
<h2 class="title">httpbin.org
<small>
<pre class="version">0.9.2</pre>
</small>
</h2>
find()
find() メソッドの中で要素名を指定することにより html の中に記述されたセレクタを見つけることができる。id でも クラス名でも指定可能。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://httpbin.org/')
id_name = r.html.find('.title', first=True)
print(id_name)
# first=True
# <Element 'h2' class=('title',)>
find()メソッドのパラメーター一覧
メソッド | 働き |
---|---|
selector | 使う CSS セレクター |
clean | HTML タグのサニタイズ |
containing | 含まれるテキスト |
first | 最初の結果だけ返すかどうか |
_encoding |
エンコード形式 |
find()メソッドの記述例
find(
selector: str = '*', *,
containing: Union[str, typing.List[str]] = None,
clean: bool = False,
first: bool = False,
_encoding: str = None
)
.attrs をつけると、class 名や id 名などの属性を表示する。
print(id_name.attrs)
# classの場合 {'class': ('title',)}
# idの場合 {'id': 'swagger-ui'}
URL に関する処理
次のコードは URL に関する情報を返すものである。.html.links にすると、リンクのリストを取得するが、.html.absolute_links は、ページ上のすべてのリンクのリストを絶対形式で取得する。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://httpbin.org/')
print(r)
# <Response [200]>
print(r.html.url)
# https://httpbin.org/
print(r.html.absolute_links)
# {''https://github.com/...', 'https://httpbin.org/...', ...}
メソッド一覧
記述法 | 対象 |
---|---|
r.html.links() | リンク |
r.html.absolute_links() | 絶対形式のリンク |
r.html.find() | CSS セレクタ |
r.html.base_url() | ベースとなる URL |
r.html.render() | JavaScript 取得 |
記述法 | 取得 |
---|---|
xxxx.text | テキストコンテンツ |
xxxx.full_text | 全文コンテンツ |
xxxx.attr | 属性(class 名や id 名) |
xxxx.html | HTML |
xxxx.absolute_links | リンク |
xxxx.search | テキスト検索 |
xxxx.xpath | XPath |
title を取得する
メタ情報のタイトルは、head > title で取得できる。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://ja.wikipedia.org/')
id_name = r.html.find('head > title', first=True)
print(id_name.text)
# Wikipedia
要素内の文章を抽出
.text パラメータをつけることで、要素内のテキストを抽出する。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://httpbin.org/')
id_name = r.html.find('.title', first=True)
print(id_name.text)
# httpbin.org
# 0.9.2
.full_text は全文コンテンツを取得する。余白と改行はそのまま表示される。
掘り下げて検索
結果に、.find をつけて、掘り下げて目的の要素を探すことができる。
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://httpbin.org/')
id_name = r.html.find('#swagger-ui', first=True)
#更にaの要素を探す
id_name.find('a')
# [<Element 'a' href='https://xxx.org' target='_blank'>,
# ...]
JavaScript を取得する
render()メソッドは、JavaScript でレンダリングされたページを取得することができるが、render()メソッドの初回実行時に、Chromium がホームディレクトリにダウンロードされる。
r.html.render()
リクエストなし
r.html.render(script=script, reload=False)
render()メソッドのパラメーター一覧
パラメーター | 処理内容 |
---|---|
retries | ページリロード回数 |
script | ページ読み込み時に実行する |
wait | ロード前の待機時間。タイムアウトを防ぐ |
scrolldown | ページスクロールの回数 |
sleep | レンダリング後のスリープ時間 |
reload | False でリロードしない |
keep_page | True でページ操作する場合 |
render()メソッドの記述例
render(
retries: int = 8,
script: str = None,
wait: float = 0.2,
scrolldown=False,
sleep: int = 0,
reload: bool = True,
timeout: Union[float, int] = 8.0,
keep_page: bool = False
)
参考:Requests-HTML: HTML Parsing for Humans (writing Python 3)! — requests-HTML v0.3.4 documentation
Python おすすめ本
スポンサード リンク
関連記事
- Python : 再帰は大きな問題が小さな問題に収束するように使う
- Python: f-string(f 文字列)と「:」の便利な使い方
- Python: bytes 型 と str 型の違い。変換方法
- Python: MySQL へ接続するモジュール mysqlclient(MySQLdb)の使い方
- Python: インポートしたときに「ModuleNotFoundError」になる場合の対処法
- Python: カウンタ。Counter()関数で要素数を計算する
- Python: BeautifulSoup 使い方(タイトル・HTML 取得など)
- Python: Requests モジュールの使い方(スクレイピング、データ収集など)
- Python: SQL の基本コマンドと sqlite3 モジュール
- Python: JSON とは何か?(loads、dumps など)
Leave a Comment