7.16.12. html_extract#
Added in version 16.1.6.
注釈
これは実験的な機能です。現時点ではまだ安定しきっていません。
7.16.12.1. 概要#
html_extractはHTMLからテキストコンテンツを抽出します。HTMLタグを削除し、<などの文字参照を展開します。
html_extractはExtractorHTMLと同じ挙動です。html_extractを使うと、HTMLのテキストコンテンツを取得できます。例えばoutput_columnsで使うとHTMLのメインコンテンツを出力したり、特定の要素を登録するために生成カラムで利用することができます。
7.16.12.2. 構文#
html_extractには必須の引数が1つとオプションのパラメーターがあります。
html_extract(html)
html_extract(html, options)
optionsには以下のキーを指定します。すべてのキー・値のペアは省略可能です。
{
"selector": selector
}
7.16.12.3. 使い方#
以下は、使い方を示すためのスキーマ定義とサンプルデータです。
実行例:
table_create Pages TABLE_NO_KEY
# [[0,1337566253.89858,0.000355720520019531],true]
column_create Pages html COLUMN_SCALAR Text
# [[0,1337566253.89858,0.000355720520019531],true]
load --table Pages
[
{"html": "<html><body>He<ll>o</body></html>"},
{"html": "<nav>Menu</nav><article>Hello</article><footer>Footer</footer>"}
]
# [[0,1337566253.89858,0.000355720520019531],2]
以下は、HTMLからテキストコンテンツを抽出する例です。HTMLタグ(<html>、<body>など)は削除され、文字参照(<と>)は展開されます。
実行例:
select Pages --output_columns 'html_extract(html)'
# [
# [
# 0,
# 1337566253.89858,
# 0.000355720520019531
# ],
# [
# [
# [
# 2
# ],
# [
# [
# "html_extract",
# null
# ]
# ],
# [
# "He<ll>o"
# ],
# [
# "MenuHelloFooter"
# ]
# ]
# ]
# ]
selectorを使うと、指定されたHTMLタグ内のコンテンツのみを抽出できます。これはページのメインコンテンツのみを抽出したいときなどに便利です。最初のレコードには<article>がないため、空のテキストが返されます。
実行例:
select Pages --output_columns 'html_extract(html, {"selector": "article"})'
# [
# [
# 0,
# 1337566253.89858,
# 0.000355720520019531
# ],
# [
# [
# [
# 2
# ],
# [
# [
# "html_extract",
# null
# ]
# ],
# [
# ""
# ],
# [
# "Hello"
# ]
# ]
# ]
# ]
html_extractは生成カラムで使えます。次の例ではHTMLのメインコンテンツをcontentカラムに自動的に登録します。
実行例:
column_create Pages content COLUMN_SCALAR Text html \
--generator 'html_extract(html, {"selector": "article"})'
# [[0,1337566253.89858,0.000355720520019531],true]
select Pages --output_columns content
# [
# [
# 0,
# 1337566253.89858,
# 0.000355720520019531
# ],
# [
# [
# [
# 2
# ],
# [
# [
# "content",
# "Text"
# ]
# ],
# [
# ""
# ],
# [
# "Hello"
# ]
# ]
# ]
# ]
7.16.12.4. 引数#
必須の引数が1つとオプションのパラメーターがあります。
7.16.12.4.1. 必須引数#
7.16.12.4.1.1. html#
htmlは対象のHTMLです。ShortText、Text、LongTextなどのテキスト型の値である必要があります。
html_extractは、このパラメーターがテキストでなければエラーを報告します。
7.16.12.4.2. 省略可能引数#
7.16.12.4.2.1. options#
optionsはJSONオブジェクトとして渡すことができます。
7.16.12.4.2.1.1. selector#
テキストコンテンツを抽出する要素を指定します。要素外のテキストコンテンツは無視されます。
これはExtractorHTMLのselectorと同じです。制限事項も同じです。詳細はselectorを参照してください。
デフォルト値はセレクタなしです。すべてのテキストコンテンツが抽出されます。
7.16.12.5. 戻り値#
html_extractは抽出されたテキストコンテンツをTextとして返します。
selectorの指定があっても、それに一致する要素がない場合はhtml_extractは空のテキストを返します。