[python] 파이썬 BeautifulSoup으로 링크 추출하기
파이썬의 BeautifulSoup 라이브러리를 사용하면 웹 페이지에서 링크를 추출하는 작업을 간단하게 할 수 있습니다. 이번 포스트에서는 BeautifulSoup을 이용하여 파이썬 코드로 링크를 추출하는 방법을 알아보겠습니다.
BeautifulSoup 설치하기
먼저 BeautifulSoup을 설치해야 합니다. 아래의 명령을 실행하여 파이썬 패키지 관리자인 pip를 이용하여 BeautifulSoup을 설치합니다.
pip install bs4
웹 페이지에서 링크 추출하기
다음은 예제로 사용할 간단한 HTML 문서입니다.
<html>
<head>
<title>링크 추출 예제</title>
</head>
<body>
<h1>링크 추출</h1>
<ul>
<li><a href="http://www.example.com">Example 1</a></li>
<li><a href="http://www.example.com">Example 2</a></li>
<li><a href="http://www.example.com">Example 3</a></li>
</ul>
</body>
</html>
이 HTML 문서에서 링크를 추출하는 파이썬 코드는 다음과 같습니다.
from bs4 import BeautifulSoup
html = """
<html>
<head>
<title>링크 추출 예제</title>
</head>
<body>
<h1>링크 추출</h1>
<ul>
<li><a href="http://www.example.com">Example 1</a></li>
<li><a href="http://www.example.com">Example 2</a></li>
<li><a href="http://www.example.com">Example 3</a></li>
</ul>
</body>
</html>
"""
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('a')
for link in links:
print(link['href'])
위 코드를 실행하면 해당 웹 페이지에서 링크를 추출하여 출력합니다.
출력 결과는 다음과 같습니다.
http://www.example.com
http://www.example.com
http://www.example.com
추가 정보
- BeautifulSoup 공식 문서: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
- 파이썬 공식 문서: https://www.python.org