開始使用免費開始

用 BeautifulSoup 將網頁轉成資料:擷取超連結

在這個練習中,你要從 BDFL 的網頁擷取超連結的 URL。過程中,你會更熟悉 soup 的 find_all() 方法。

本練習屬於課程

Python 資料匯入進階

檢視課程

練習說明

  • 使用 find_all() 方法在 soup 中找出所有超連結。記住,超連結由 HTML 標籤 <a> 定義,但傳給 find_all() 時不含角括號;將結果儲存到變數 a_tags
  • 變數 a_tags 是一個結果集合:接下來請用 for 迴圈逐一列舉並印出每個超連結實際的 URL。為此,對於 a_tags 中的每個元素 link,請 print() link.get('href')

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import packages
import requests
from bs4 import BeautifulSoup

# Specify url
url = 'https://www.python.org/~guido/'

# Package the request, send the request and catch the response: r
r = requests.get(url)

# Extracts the response as html: html_doc
html_doc = r.text

# create a BeautifulSoup object from the HTML: soup
soup = BeautifulSoup(html_doc)

# Print the title of Guido's webpage
print(soup.title)

# Find all 'a' tags (which define hyperlinks): a_tags


# Print the URLs to the shell
for ____ in ____:
    ____
編輯並執行程式碼