XPATH の text() で親要素から直接選択する
この演習では、前と同じ表を扱います。今回は、かっこ内の機能情報を独立した列として取り出し、俳優名、役名、機能の3列を持つデータフレームを抽出します(2列ではありません)。
そのために、動画で紹介した特定の XPATH 関数を html_table() の代わりに使います。html_table() は、ここでのように HTML の table 要素の構造が整っていないと、実務ではうまく動かないことが多いからです。
参考として、表の HTML 抜粋を再掲します。
<table>
<tr>
<th>Actor</th>
<th>Role</th>
</tr>
<tr>
<td class = 'actor'>Jayden Carpenter</td>
<td class = 'role'><em>Mickey Mouse</em> (Voice)</td>
</tr>
...
</table>
この演習では、roles_html 変数に table 要素を含む HTML ドキュメントが入っています。
この演習はコースの一部です
Rで学ぶWebスクレイピング
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Extract the actors in the cells having class "actor"
actors <- roles_html %>%
html_elements(xpath = '//table//td[@class = "actor"]') %>%
html_text()
actors
# Extract the roles in the cells having class "role"
roles <- roles_html %>%
html_elements(xpath = '//table//td[@class = "___"]/___') %>%
___()
roles