使用 BeautifulSoup 將網頁轉成資料:擷取文字
如先前所說,在接下來的練習中,你會學到從 HTML soup 擷取資訊的基本技巧。這一題要你從 BDFL 的網頁擷取文字,並印出該網頁的標題。
本練習屬於課程
Python 資料匯入進階
練習說明
- 在範例程式碼中,HTML 回應物件
html_doc已經建立:你的第一個任務是用BeautifulSoup()進行轉換(Soupify),並將產生的 soup 指派給變數soup。 - 使用屬性
title從 HTML soupsoup擷取標題,並將結果指派給guido_title。 - 使用
print()函式在終端機印出 Guido 網頁的標題。 - 使用方法
get_text()從 HTML soupsoup擷取文字,並指派給guido_text。 - 按下送出以在終端機印出 Guido 網頁的文字。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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)