Zacznij terazZacznij za darmo

Bezpośrednie pobieranie danych z elementu nadrzędnego za pomocą funkcji XPATH text()

W tym ćwiczeniu pracujesz z tą samą tabelą. Tym razem wyodrębnisz informacje o funkcji postaci (podane w nawiasach) do osobnej kolumny, więc musisz uzyskać ramkę danych z nie dwiema, lecz trzema kolumnami: aktorzy, role i funkcje.

Aby to zrobić, zastosuj konkretną funkcję XPATH, którą pokazano w filmie – zamiast html_table(), która w praktyce często nie działa, gdy element table w HTML nie jest dobrze ustrukturyzowany – tak jak ma to miejsce tutaj.

Dla przypomnienia, poniżej fragment kodu HTML tabeli:

<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>

W tym ćwiczeniu zmienna roles_html zawiera dokument HTML wraz z elementem table.

To ćwiczenie jest częścią kursu

Web Scraping w R

Zobacz kurs

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

# 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
Edytuj i uruchom kod