Web Crawling/BeautifulSoup

정적 웹 페이지 스크래핑 - requests, BeautifulSoup 활용

js-kkk 2025. 2. 23. 18:03

VScode에 02_static-web-page 폴더 만든 후 그 안에 01_request_bs.py 생성

 

 

(아래 코드에서는 selenium 설치는 필요없음, requests와 beautifulsoup4 만 설치할 것 )

# 정적 페이지 웹 스크래핑 -> requests, beautifulsoup
# 정적 페이지 : 요청한 url에서 응답받은 html을 그대로 사용한 경우 (Server Side Rendering)

import requests
from bs4 import BeautifulSoup

def web_request(url):
    response = requests.get(url)
    print(response)     # <Response [200]>
    print("=========1=========")
    print(response.status_code)     # 200 (응답코드)
    print("=========2=========")
    print(response.text)             # html 
    return response

# url = "https://www.naver.com" 
# response = web_request(url)

with open('../html_sample.html','r',encoding='utf-8') as f:
    html = f.read()

bs = BeautifulSoup(html, 'html.parser')
# print(bs)
# print(type(bs))

def test_find():
    # find
    tag = bs.find('li')
    print(tag)
    print(type(tag))


    # find all 
    tags = bs.find_all('section', {'id':'section1'})
    print(tags)
    print(type(tags))

test_find()

 

 

 

내용 추가 02/24

import requests 
from bs4 import BeautifulSoup
from datetime import datetime
from urllib.request import urlretrieve

# 스크랩한 뉴스 정보를 담은 NewsEntry Class
class NewsEntry:
    def __init__(self, title, href, img_path):
        self.title = title
        self.href = href
        self.img_path = img_path

    def __repr__(self):  # 
        return f'NewsEntry<title={self.title}, href={self.href}, img_path={self.img_path}>' 
    
    

# 1. request -> url 요청
keyword = input("뉴스 검색 키워드 입력:")
url = f"https://search.naver.com/search.naver?ssc=tab.nx.all&where=news&sm=tab_jum&query={keyword}"    
                     #     ? 이후에 쿼리스트링 시작   = 기준으로 왼쪽이 키, 오른쪽이 값
response = requests.get(url)

# 2. html 응답
html = response.text

# 3. BeautifulSoup 객체 생성
bs = BeautifulSoup(html, 'html.parser')

# 4. li.bx 반복순회 > .news_content > 두 번째 a 태그 
news_contents = bs.select('div.news_contents')
# print(len(news_contents))

# 5. href속성: 링크, text: 뉴스제목, 

news_list = []
for i, news_content in enumerate(news_contents):
    a_tag = news_content.select_one('a.news_tit')
    title = a_tag.text
    href = a_tag['href']

    img_tag = news_content.select_one('img.thumb')  
    img_lazysrc = img_tag['data-lazysrc']
    if img_lazysrc.startswith("http"):
        img_dir = "C:\\encore_skn11\\03_web_crawling\\02_static-web-page\\images"
        today = datetime.now().strftime('%y%m%d')  # 파일명 생성을 위한 오늘 날짜 
        filename = f'{img_dir}/{today}_{i}.jpg'    # 파일명 (저장할 파일 확장자까지)
        urlretrieve(img_lazysrc,filename)          # 파일 저장

    news_entry = NewsEntry(title, href, filename)
    news_list.append(news_entry)

# 결과 출력
for news in news_list:
    print(news)

 

'Web Crawling > BeautifulSoup' 카테고리의 다른 글

BeautifulSoup 이란?  (2) 2025.02.23