본문 바로가기
IT종합/Web Technic

다음 웹 사이트 검색결과 크롤링 해오기 - Python, BeautifulSoup4, requests

by 우동이 2023. 2. 21.
300x250

작업환경

  • Visual Studio Code 1.74.3
  • Python 3.11.1
  • Beautifulsoup4 - 4.11.2

들어가기 전

크롤링은 어떤 웹 사이트에서든 가능하나 네이버의 경우에는 웹 로직이 계속 변경되어서

bs4와 request 만으로는 크롤링이 불가능하고 pandas와 selenium 모듈을 사용해야 되는 걸로 알고 있습니다.

거기다가 로직 변경이 계속 이루어져서 주기적으로 코드 최신화가 되어야 합니다.


1. Requests 모듈을 이용한 GET Request 예제

 

import requests

url = "https://www.naver.com/"
response = requests.get(url)

print("STATUS CODE : ", response.status_code)

 

HTTP/HTTPS는 GET과 POST 메서드를 활용해 Request/Response 요청/응답을 수행합니다.

 

  • response.status_code : 응답.상태코드
  • requests.get() : GET 메서드로 요청
  • requests.post() : POST 메소드로 요청

 

 

이 코드를 통해 얻는 결괏값은 현재 Naver 웹사이트에 보낸 요청이 정상(200)적으로 응답되었다는 뜻입니다.

 

흔히들 볼 수 있는 404 에러의 경우는 요청한 웹사이트가 존재하지 않을 경우(NotFound) 발생하는 에러코드입니다.

 


2. Requests 모듈을 이용해 정보 요청해서 출력하기

 

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts")
if response.status_code == 200:
    print("정상적으로 연결되었습니다.")

posts = response.json()

for post in posts:
    print(f"글 제목: {post['title']}")
    print(f"글 내용: {post['body']}")
    print()

    comment_response = requests.get(f"https://jsonplaceholder.typicode.com/posts/{post['id']}/comments")
    comments = comment_response.json()

    for comment in comments:
        print(f"댓글 작성자: {comment['name']}")
        print(f"댓글 내용: {comment['body']}")
        print()

 

이 코드는 jsonplaceholder 사이트에서 제공되는 게시글과 댓글 데이터를

json형태로 불러와서 Python의 딕셔너리 자료형으로 파싱 합니다.

 

  • response.json() - 데이터를 json 형태로 가져옵니다.

 

 

위 결과는 json 데이터를 python 딕셔너리로 파싱 해서 출력된 댓글과 게시물의 내용 데이터입니다.

 

 


3. BeautifulSoup4 모듈을 이용해 다음 검색결과 가져오기(단일, 블로그)

 

import requests
from bs4 import BeautifulSoup

search_terms = "google"  
url = f"https://search.daum.net/search?w=blog&nil_search=btn&DA=NTB&enc=utf8&q={search_terms}"

response = requests.get(url)

if response.status_code == 200:
    soup = BeautifulSoup(response.content, "html.parser")
    posts = soup.find_all("li", {"class": "sh_blog_top"})

    for post in posts:
        title = post.find("a", {"class": "sh_blog_title"}).get("title")
        url = post.find("a", {"class": "sh_blog_title"}).get("href")
        description = post.find("div", {"class": "sh_blog_passage"}).text.strip()

        print(f"Title: {title}")
        print(f"URL: {url}")
        print(f"Description: {description}")
        print()
else:
    print("Search Fail")

 

 

위 코드는 bs4 모듈을 이용해서 다음 포털에서의 검색결과를 가져옵니다.

위에서는 google에 대한 한 개의 검색결과만을 가져오며 가져오는 항목에는 <class> 태그의 sh_blog_title, sh_blog_passage 두 값을 가져오며 각각 제목값과 설명값입니다.

 

또한 크롤링해오는 검색결과는 블로그 탭 한정입니다.

URL을 자세히 살펴보면 w=blog 인 것을 알 수 있는데

w=tot일 경우 통합검색결과입니다.

 


4. BeautifulSoup4 모듈을 이용해 다음 검색결과 가져오기(다중, 블로그)

 

import requests
from bs4 import BeautifulSoup

search_terms = "치과" 

for page in range(1, 11):
    url = f"https://search.daum.net/search?w=blog&nil_search=btn&DA=NTB&enc=utf8&q={search_terms}&page={page}"

    response = requests.get(url)

    if response.status_code == 200:
        soup = BeautifulSoup(response.content, "html.parser")
        posts = soup.find_all("li", {"class": "fst"})

        for post in posts:
            title = post.find("a", {"class": "f_link_b"}).text
            url = post.find("a", {"class": "f_link_b"}).get("href")
            description = post.find("p", {"class": "f_eb desc"}).text.strip()

            print(f"Title: {title}")
            print(f"URL: {url}")
            print(f"Description: {description}")
            print()
    else:
        print(f"Search Fail-Page Num : {page}")
        break

 

for문으로 page를 제어해 여러 개의 결괏값을 크롤링해왔습니다.

이 코드의 경우에는 직접 테스트해보면 아시겠지만 각 페이지마다 모든 결과를 가져오지는 않고

페이지별 최상단 게시글 한 개씩 크롤링해옵니다.

 

 

 

 

이상 requests, bs4를 활용해 크롤링 코드를 짜봤습니다.

다음번에는 flask로 크롤링 결과를 웹페이지에 노출시켜 보도록 하겠습니다.


다른 글

 

Criminal API 사용법

 

 

WireShark 모의해킹 시나리오

 

 

Kali Linux 툴로 도메인 조회하기

300x250

댓글