แปลงหน้าเว็บเป็นข้อมูลด้วย BeautifulSoup: การดึง hyperlink
ในแบบฝึกหัดนี้ จะได้เรียนรู้วิธีดึง URL ของ hyperlink จากหน้าเว็บของ BDFL โดยจะได้ทำความคุ้นเคยกับเมธอด find_all() ของ soup เป็นอย่างดี
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การนำเข้าข้อมูลด้วย Python ระดับกลาง
คำแนะนำการฝึกหัด
- ใช้เมธอด
find_all()เพื่อค้นหา hyperlink ทั้งหมดในsoupโดยจำไว้ว่า hyperlink กำหนดด้วย HTML tag<a>แต่เมื่อส่งให้find_all()ไม่ต้องใส่วงเล็บมุม แล้วเก็บผลลัพธ์ไว้ในตัวแปรa_tags - ตัวแปร
a_tagsคือชุดผลลัพธ์ ขั้นตอนต่อไปคือวนซ้ำผ่านforloop แล้วพิมพ์ URL จริงของ hyperlink แต่ละรายการ โดยสำหรับทุก elementlinkในa_tagsให้ใช้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 ____:
____