BeautifulSoup으로 웹페이지를 데이터로 바꾸기: 하이퍼링크 가져오기
이번 연습에서는 BDFL의 웹페이지에서 하이퍼링크의 URL을 추출하는 방법을 알아봅니다. 이 과정을 통해 find_all() 메서드와 한층 친숙해질 거예요.
이 연습은 강의의 일부입니다
Intermediate Importing Data in 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 ____:
____