프로그래밍언어/Python

파이썬 웹 크롤링(Python web crawling) 만들기 웹 페이지 html 크롤링 FastAPI로 빠르게만드는 Rest API 호출 Json Response 처리 Step 6

by 앵과장 2022. 10. 21. 14:56
반응형

Setp5 까지 잘따라오셨다면 Github 에 Repogitory 만들어지고 내컴퓨터에는 Poetry 가상환경으로

아래 pyproject.toml 이 만들어져있어야 합니다.

 

github에 코드올려두었으니 clone하시면됩니다.

https://github.com/lswteen/webcrawling

 

GitHub - lswteen/webcrawling

Contribute to lswteen/webcrawling development by creating an account on GitHub.

github.com

1.pyproject.toml 이 생성

[tool.poetry]
name = "crawling"
version = "0.0.1"
description = "python web crawling"
authors = ["renzo"]
license = "mit"
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.10"
fastapi = "^0.85.1"
requests = "^2.28.1"
beautifulsoup4 = "^4.11.1"
selenium = "^4.5.0"
uvicorn = "^0.19.0"

[tool.poetry.group.dev.dependencies]
requests = "^2.28.1"
beautifulsoup4 = "^4.11.1"
selenium = "^4.5.0"
uvicorn = "^0.19.0"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

poetry 가상환경에 위에서 정의된 dependencies 패키지 들이설치되어있어야합니다.

poetry add fastapi

poetry add requests

poetry add beautifulsoup4

poetry add selenium

poetry add uvicorn

uvicorn실행 

uvicorn main:app --reload --port 8000

(crawling-py3.10) (base) lswteen@lswteenui-iMac webcrawling % uvicorn main:app --reload --port 8000
INFO:     Will watch for changes in these directories: ['/Users/lswteen/workspace/webcrawling']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [5421] using StatReload
INFO:     Started server process [5423]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

3.main.py 파일 생성

import requests
from fastapi import FastAPI # FastAPI 모듈 가져오기
from bs4 import BeautifulSoup as bs

app = FastAPI() # 객체 생성

@app.get("/") # Route Path
def test_index():
    # Json 타입으로 값 반환
    return {
	    "Python": "Framework",
	}

@app.get("/something")
def something():
    return {
        "Something": "Page",
    }

@app.get("/naver")
def naver():
    url = 'https://kin.naver.com/search/list.nhn?query=%ED%8C%8C%EC%9D%B4%EC%8D%AC'
    response = requests.get(url)
    answer = ''
    if response.status_code == 200:
        html = response.text
        soup = bs(html, 'html.parser')
        answer = soup
    else:
        answer = response.status_code
    return {
        "html" : print(answer)
    }

@app.get("inflearn")
def inflearn():
    url = 'https://www.inflearn.com/course/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%8B%A4%EC%9A%A9%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8'
    return {
        "page" : "inflearn",
        "title" : "a",
        "imagePath" : "image",
        "contents" : "contents",
        "link" : url
    }

 

 

4.페이지 확인

http://localhost:8000/docs#/default/inflearninflearn_get

이렇게 했는데 안되면 Step4 부터 다시 따라오시면됩니다. 또안되면 Step3 으로 가셔서 보시고 오시면됩니다.

그래도 안되면 댓글주세요 :)

그럴수있져 하다보면 막 안되기도 하고 상황때문에 그럴수도 있습니다.

 

파이썬 웹 크롤링(Python web crawling) 만들기 poetry 가상환경 설정 Step 4

파이썬으로 conda 가상환경을 구성하고 fastapi 프레임워크를 기반으로 github에 작업해보려고하니 파이썬은 패키지 구성이나 버전등을 구성할수 있는 스켈레톤형태의 구조가 필요한데 github에 올릴

angryfullstack.tistory.com

 

파이썬 웹 크롤링(Python web crawling) 만들기 poetry fastapi uvicorn 실행 드디어 파이썬 가상환경 설정완

conda 환경부터 시작해서 github연결 시도 하다가 poetry 가상환경 으로 진행후 연결설정한뒤에 git까지 진행되었습니다. 그이후 터미널로 진행하려니 쉽지가 않아서 pycharm CE 설치까지 진행되셨나요?

angryfullstack.tistory.com

여기까지 되셨다면 본격적으로 FastAPI를 통해서 웹크롤링된 특정 필드들을 API Json으로 작업해 보도록 하겠습니다.

 

인프런 상세화면 크롤링 해보기

https://www.inflearn.com/course/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%8B%A4%EC%9A%A9%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8

 

파이썬으로 뭘 만들지? 남박사의 파이썬 알쓸파잡 - 인프런 | 강의

우리가 당연히 알고 있거나 흔하게 접하는 프로그램 혹은 파일 구조 등을 파이썬으로 보다 심도 있게 파고드는 강좌 입니다., - 강의 소개 | 인프런...

www.inflearn.com

파이썬 으로 웨크롤링을 진행하는중이니 인프런의 파이썬 강의 상세에서 

제목, 내용, 이미지 3가지를 BeautifulSoup 해보도록 하겠습니다.

 

일단 화면에 Html을 개발자도구로 분석해보겠습니다.

Img Element src 속성 

 

<div class="cd-header__thumbnail ">
          <img src="https://cdn.inflearn.com/public/courses/324595/cover/4a9cc839-a6a3-4445-b73d-8bc54a2553b9/324595-eng.png" alt="Thumbnail">
          
    <div class="thumbnail-button-cover thumbnail-bottom-button-cover e-preview">
      <button class="thumbnail-bottom-button">
        <span class="infd-icon"><svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#ffffff" d="M6.333 10.39V5.61c0-.263.292-.422.514-.28l3.717 2.39c.204.13.204.43 0 .56l-3.717 2.39c-.222.142-.514-.017-.514-.28z"></path><path fill="#ffffff" fill-rule="evenodd" d="M8 1.667C4.502 1.667 1.667 4.502 1.667 8S4.502 14.333 8 14.333 14.333 11.498 14.333 8 11.498 1.667 8 1.667zM.667 8C.667 3.95 3.95.667 8 .667c4.05 0 7.333 3.283 7.333 7.333 0 4.05-3.283 7.333-7.333 7.333C3.95 15.333.667 12.05.667 8z" clip-rule="evenodd"></path></svg></span>
        <span class="thumbnail-bottom-button__highlight">8개</span> 무료
        보기
      </button>
    </div>
        </div>

해당 div엘리먼트 <div class="cd-header__thumbnail"> 하위 자식엘리먼트에 img src안에 링크값을 모르겠다면

google에 검색해보세요

 

키워드 : BeautifulSoup find div class 

키워드 : BeautifulSoup find img src

 

이렇게 치면 우리의 구세주 stack overflow에서확인 가능합니다.

    image = bsObject.find('div',class_='cd-header__thumbnail').find('img')['src']

 그다음 title

<div class="cd-header__title-container">
        <h2 class="cd-header__title">파이썬으로 뭘 만들지? 남박사의 파이썬 알쓸파잡</h2>
        
      </div>
    title = bsObject.find('h2',class_='cd-header__title').get_text()

그다음 contents

<p class="cd-body__description">우리가 당연히 알고 있거나 흔하게 접하는 프로그램 혹은 파일 구조 등을 파이썬으로 보다 심도 있게 파고드는 강좌 입니다.</p>
    contents = bsObject.find('p',class_='cd-body__description').get_text()

이제 이거를 fastAPI 를 이용해서 Json으로 만들어서 API호출시 나오게하면됩니다.

@app.get("/inflearn")
def inflearn():
    url = 'https://www.inflearn.com/course/%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%8B%A4%EC%9A%A9%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8'
    response = requests.get(url)
    bsObject = bs(response.text, 'html.parser')

    title = bsObject.find('h2',class_='cd-header__title').get_text()
    image = bsObject.find('div',class_='cd-header__thumbnail').find('img')['src']
    contents = bsObject.find('p',class_='cd-body__description').get_text()

    return {
        "page" : "inflearn",
        "title" : title,
        "imagePath" : image,
        "contents" : contents,
        "link" : url
    }

어때요 참 쉽죠 !!

제가볼때 개발시작하는거라면 Python추천합니다. java로 이거 짤라면 정말 한 5배는 힘들것 같네요

개발환경만 conda 부터 시작하면 poetry 꼬박 2일날렸는데

개발은 1시간만에 짠것 같네요 !!

 

관련 내용은 상단에 github참고하시면됩니다.

즐거운 파이썬 웹크롤링공부 되셨으면 좋겠습니다.

다음번에는 어떤걸 해볼까여 단건 처리는 해봤으니 리스트로 긁어오는걸 구현해봐야겠네요