Mengubah halaman web menjadi data dengan BeautifulSoup: mengambil teks
Sesuai janji, pada latihan-latihan berikut, Anda akan mempelajari dasar-dasar mengekstrak informasi dari HTML soup. Pada latihan ini, Anda akan mencari cara untuk mengekstrak teks dari halaman web BDFL, sekaligus mencetak judul halamannya.
Latihan ini adalah bagian dari kursus
Mengimpor Data Tingkat Menengah di Python
Petunjuk latihan
- Pada kode contoh, objek respons HTML
html_docsudah dibuat: tugas pertama Anda adalah membuatnya menjadi Soup menggunakan fungsiBeautifulSoup()dan menetapkan soup yang dihasilkan ke variabelsoup. - Ekstrak judul dari HTML soup
soupmenggunakan atributtitledan tetapkan hasilnya keguido_title. - Cetak judul halaman web Guido ke shell menggunakan fungsi
print(). - Ekstrak teks dari HTML soup
soupmenggunakan metodeget_text()dan tetapkan keguido_text. - Tekan Kirim untuk mencetak teks dari halaman web Guido ke shell.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
# Import packages
import requests
from bs4 import BeautifulSoup
# Specify url: url
url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Extract the response as html: html_doc
html_doc = r.text
# Create a BeautifulSoup object from the HTML: soup
# Get the title of Guido's webpage: guido_title
# Print the title of Guido's webpage to the shell
# Get Guido's text: guido_text
# Print Guido's text to the shell
print(guido_text)