用 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 ____:
____