使用 XPATH 的 text() 從父層元素直接擷取
在這個練習中,你會繼續處理同一個表格。這次,你要把括號中的 function 資訊拆出成獨立欄位,所以需要擷取出含有三個欄位的資料框:actors、roles,以及 functions,而不是只有兩個欄位。
為了達成這個目標,你需要使用影片中介紹的特定 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 的網頁爬蟲
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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