當表格結構不佳時,html_table() 的侷限
有時,你只想選到父元素的直接子節點文字。不過在下面這個範例表格裡,角色名稱本身被包在 em 標籤中;而其功能(例如「Voice」)也和 em 片段放在同一個 td 元素裡,這樣對查詢資料並不理想。
以下是部分 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>
在這個練習中,你會嘗試用一個熟悉的 rvest 函式來擷取表格。透過這麼做,你會看出它的限制。
變數 roles_html 包含了帶有該表格的文件。
本練習屬於課程
R 的網頁爬蟲
練習說明
- 嘗試使用你在第 1 章學過的函式,從該表格擷取出一個資料框。
- 檢視產生的資料框。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Extract the data frame from the table using a known function from rvest
roles <- roles_html %>%
html_element(xpath = "//___") %>%
___()
# Print the contents of the role data frame
___