使用 XPATH 的 text() 从父元素直接选择
在本练习中,您将继续处理同一张表。这一次,您需要把括号中的职能信息单独提取成一列,因此要提取的不是两列,而是三列数据框: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