BeautifulSoup を使ってwebページをデータに変換する:ハイパーリンクの取得
この演習では、BDFL のwebページからハイパーリンクの URL を取得する方法を学びます。その過程で、 メソッド 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 ____:
____