시작하기무료로 시작하기

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
코드 편집 및 실행