**kwargs/파이썬

파이썬 웹 스크랩퍼 만들기

너알둬 2020. 12. 29. 23:12
반응형

2020/12/29 - [**kwargs/파이썬] - 파이썬 독학 시작

 

파이썬 독학 시작

올해 5월 루비온레일즈(Ruby on Rails) 독학으로 백엔드를 처음 접해봤다. 당시 구현하고 싶었던 서비스가 있었고 해당 서비스에 DB가 필요하여 가장 쉽다는 언어로 선택한 것이었다. 그러고 잠시 프

kpalace.tistory.com

웹 크롤링 관련 유튜브를 지나가다 본 적이 있었다.

배워두면 두고두고 쓸 수 있을 능력이라 가지고 싶었다.

 

위의 이전 글처럼 노마드코더의 힘을 빌려 배워봤다.

 

강의의 디테일한 내용은 생략하되 내가 새로 배운 것들만 요약해서 기억에 남도록 RECAP해본다.

 

1) Repl.it

 

웹상에서 개발자 환경을 구축해주는 사이트이다.

이전에는 구름 IDE를 사용하고 있었으니 해당 사이트가 더 가볍고 쓰기 편한 것 같다.

 

해당 사이트에서 파이썬을 구동했다.

 

repl.it/

 

The collaborative browser based IDE

Repl.it is a simple yet powerful online IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin, QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript,

repl.it


2) Packages (Library)

 

A. Requests

 

requests.readthedocs.io/en/master/

 

Requests: HTTP for Humans™ — Requests 2.25.1 documentation

Requests: HTTP for Humans™ Release v2.25.1. (Installation) Requests is an elegant and simple HTTP library for Python, built for human beings. Behold, the power of Requests: >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass')) >>> r.

requests.readthedocs.io

HTTP를 인간 친화적으로 손쉽게 요청할 수 있다.

import requests

URL = "사이트 주소"
page = requests.get(f"{URL}")

# f"{변수}" / 쌍따움표 앞에 f를 붙이면 {}를 사용하여 변수도 넣어서 표기할 수 있다.

 

 


 

B. eautifulSoup

 

www.crummy.com/software/BeautifulSoup/bs4/doc/

 

Beautiful Soup Documentation — Beautiful Soup 4.9.0 documentation

Non-pretty printing If you just want a string, with no fancy formatting, you can call str() on a BeautifulSoup object (unicode() in Python 2), or on a Tag within it: str(soup) # ' I linked to example.com ' str(soup.a) # ' I linked to example.com ' The str(

www.crummy.com

HTML과 XML 파일로부터 데이터를 뽑아내기 위한 파이썬 라이브러리이다.

(써보니 정말 아름다운 찌개다)

 

보통 requests와 함께 html을 text로 변환하여 가져오는거 같다.

import requests
from bs4 import BeautifulSoup

URL = "사이트 주소"
page = requests.get(f"{URL}")
soup = BeautifulSoup(page.text,'html.parser')

변수 soup에 해당 사이트의 크롬 개발자 도구 Elements탭 그대로 가져온다.

가져온 HTML 파일에서 필요한 태그 및 ID를 찾아 뽑아낼 수 있다.

 

<자주쓰는 활용법 정리>

# example

soup.find_all('a')
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
#  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
#  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

soup.find(id="link3")
# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

html.find_all("div",{"class":"class_name"})
# div 태그 중에 클래스네임이 같으것만 가져옴

html.find("h2",{"class":"class_name"}).find("a")["title"]
# h2 태그 중에 클래스네임이 같으것만 가져온 것중에서 a태그의 title 값을 가져옴

head_tag.contents
# [<title>The Dormouse's story</title>]
head_tag.string
# 'The Dormouse's story'

markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup, 'html.parser')
soup.get_text()
'\nI linked to example.com\n'
# soup.get_text(strip=True)
'I linked to example.com'
# strip=True 넣으면 쓸 때 없는 공백제거

 


C. SV

 

(Comma Separated Value)

쉼표를 기준으로 항목을 구분하여 저장한 데이터를 말한다.

import csv

def save_to_csv(jobs):
  file = open("jobs.csv", mode = "w", encoding = "utf-8")
  writer = csv.writer(file)
  writer.writerow(["title","company","location","link"])
  for job in jobs:
    writer.writerow(list(job.values()))
  return

import csv를 해주면

csv 파일 속 데이터를 open, csv.writer(), writerow() 함수 등 다양한 방법으로 만질 수 있다.


D. Flask

 

파이썬으로 작성된 마이크로 웹 프레임워크의 하나로 가벼운 프로젝트에 쓴다고 한다.

 

flask.palletsprojects.com/en/1.1.x/

 

Welcome to Flask — Flask Documentation (1.1.x)

 

flask.palletsprojects.com

예시

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def home():
  return render_template("abc.html")
    
app.run(host="0.0.0.0")
#local host 주소

※ from의 flask 'f'는 소문자, import Flask 'F'는 대문자

※ @app 밑에는 오는 첫번째 함수를 실행함

※ render_template 사용 시,

같은 파이썬 루트에 폴더명 templates( 's' 빼먹으면 안됨 )에 abc이름으로 된 html파일을 만들어놔야 페이지 연결됨


 

단시간 다양하게 배웠다.

복습겸 요정도로 정리하고 생각나거나 추가 할 기역이 있으면 돌아오겠다.

 

 

이후에는 배운 지식(웹 크롤링)을 통해 구현할 수 있는 간단한 서비스를 만들어 볼 생각이다.

좋았쓰

반응형