Python을 이용한 웹 스크래핑 기초

이 섹션에서는 Python으로 웹 페이지를 쉽게 스크래핑할 수 있도록 도와주는 여러 모듈을 살펴봅니다.

  • webbrowser: Python 표준 라이브러리의 일부로, 지정된 웹 페이지를 열기 위해 브라우저를 실행합니다.
  • requests: 인터넷에서 파일과 웹 페이지를 다운로드하는 데 사용됩니다.
  • Beautiful Soup: 웹 페이지를 작성하는 데 사용되는 HTML을 파싱하는 데 특화되어 있습니다.
  • selenium: 웹 브라우저를 시작하고 제어합니다. 폼을 작성하고 브라우저 내에서 마우스 클릭을 시뮬레이션할 수 있습니다.

1. webbrowser 모듈을 활용한 구글 지도 주소 일괄 열기

이 예제에서는 명령줄 인수 또는 클립보드에서 거리 주소를 가져와 해당 주소의 Google 지도 페이지를 가리키도록 웹 브라우저를 엽니다.

이 코드는 다음과 같은 작업을 수행해야 합니다:

  1. sys.argv에서 명령줄 인수를 읽습니다.
  2. 또는 클립보드에서 주소를 읽습니다.
  3. webbrowser.open() 함수를 호출하여 외부 브라우저를 엽니다.

import webbrowser
import sys
import pyperclip

if len(sys.argv) > 1:
    # 명령줄에서 주소 가져오기
    location = " ".join(sys.argv[1:])
else:
    # 클립보드에서 주소 가져오기
    location = pyperclip.paste()

webbrowser.open(f'https://www.google.com/maps/place/{location}')

2. requests 모듈을 사용한 웹 파일 다운로드

2.1 requests.get() 함수로 웹 페이지 다운로드


import requests

url = "https://www.baidu.com/notfound.html"
try:
    response = requests.get(url)
    response.raise_for_status()  # HTTP 오류가 발생하면 예외를 발생시킵니다.
    print("Successfully downloaded the page.")
except requests.exceptions.RequestException as e:
    print(f'An error occurred: {e}')

requests.get() 함수를 사용하여 웹 페이지를 다운로드합니다. raise_for_status() 함수는 페이지 다운로드 성공 여부를 확인합니다. 성공하면 아무런 동작도 하지 않지만, 실패하면 오류 메시지를 반환합니다.

2.2 다운로드한 파일 저장하기


import requests

file_url = "https://www.gutenberg.org/cache/epub/1112/pg1112.txt"
output_filename = "romeo_and_juliet.txt"

try:
    response = requests.get(file_url)
    response.raise_for_status()
    with open(output_filename, 'wb') as file_handle: # 'wb' 모드는 바이너리 쓰기를 의미합니다.
        for chunk in response.iter_content(chunk_size=8192): # 더 작은 청크 크기 사용
            file_handle.write(chunk)
    print(f"File '{output_filename}' downloaded successfully.")
except requests.exceptions.RequestException as e:
    print(f'An error occurred during download: {e}')

response.iter_content()은 다운로드된 웹 페이지 콘텐츠의 스트림을 반환합니다. for 루프를 사용하여 콘텐츠를 읽고 파일에 씁니다.

3. BeautifulSoup 모듈을 사용한 HTML 파싱

Beautiful Soup는 HTML 페이지에서 정보를 추출하는 데 사용되는 라이브러리입니다. bs4 (Beautiful Soup 4)라고도 합니다. 설치하려면 명령줄에서 pip install beautifulsoup4를 실행해야 합니다. 설치 시 이름은 beautifulsoup4이지만, 임포트할 때는 import bs4를 사용합니다.


import requests
from bs4 import BeautifulSoup

url = "http://www.gongguanzhijia.com/article/5504.html"
try:
    response = requests.get(url)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')

    # 'h3' 태그 모두 선택
    header_elements = soup.select('h3')

    if header_elements:
        first_header = header_elements[0]
        print("First h3 tag content:", str(first_header))
        print("Text of first h3 tag:", first_header.get_text())
        print("Attributes of first h3 tag:", first_header.attrs)
    else:
        print("No 'h3' tags found on the page.")

except requests.exceptions.RequestException as e:
    print(f'Error fetching URL: {e}')
except Exception as e:
    print(f'An error occurred during parsing: {e}')

  1. requests.get() 함수로 HTML 웹 페이지를 다운로드합니다.
  2. BeautifulSoup() 함수를 사용하여 HTML 웹 페이지 소스를 가져옵니다.
  3. select() 메서드를 사용하여 원하는 태그(예: 'h3')를 찾습니다.
  4. str()은 태그 자체의 전체 내용을 반환합니다.
  5. get_text()는 태그 내부의 텍스트만 추출합니다.
  6. attrs는 태그의 속성들을 딕셔너리 형태로 반환합니다.

태그: Web Scraping python requests BeautifulSoup webbrowser

7월 22일 11:55에 게시됨