본문 바로가기
기초/웹 개발 왕초보 입문

3주차_서버 만들기2

by Hyeon_E 2022. 12. 19.

파이썬 패키지 살펴보기

https://pypi.org/

python 패키지를 발표(공개)하는 곳

 

PyPI · The Python Package Index

The Python Package Index (PyPI) is a repository of software for the Python programming language.

pypi.org

 

터미널에서 패키지 설치


웹 스크래핑(크롤링)

크롤링: 프로그램을 이용하여 특정 사이트에 접속해 데이터를 수집하는 것

사람이 하는것보다 훨씬 빠르고 많이 접속할 수 있기 때문에 서비스사이트들이 부담이 갈 수 있음.

크롤링 코드를 작성할때는 무분별하게 접속하지 않게 해야함

- 즉 스크래핑과 같은 데이터 수집 기술은 수집대상 서비스에 부하를 주는 행위이니 빈번한 사용을 자제해야 함

crawl.py
0.00MB

import requests
from bs4 import BeautifulSoup

import: 패키지를 가지고 올때 사용하는 구문

            from을 쓰는 경우에는 import에서 가져온 패키지 안에 일부분을 사용한다는 의미

 

res = requests.get("http://www.yes24.com/24/category/bestseller")
soup = BeautifulSoup(res.text, "html.parser")

BeautifulSoup안에 2개의 값을 전달

첫번째 값은 res변수가 가지고 있는 텍스트값, 즉 주소에 접속했을때 받은 HTML코드

html.parser는 BeautifulSoup이 약속을 해놓은 값. HTML코드로 되어있으니 분석해 달라는 뜻

for i in range(40):
    idx = str(i+1)
    if idx == "19":
        idx = "19_line"
    elif idx == "20":
        idx = "20_line"

    sstr = "#bestList > ol > li.num" + idx + " > p:nth-child(3) > a"
    ts = soup.select_one(sstr)
    print(ts.text)

반복문을 이용해 40번 반복함

변수 idx에 변수 i +1의 값을 값으로 넣어줌. 문자열이 필요함으로 맞춰주기 위해 str함수를 이용하여 문자열로 변경

i+1값을 하는 이유는 1부터 필요한데 i는 0부터 시작하기 때문

이때 예외처리로 19와 20일때는 다른 문자열을 넣어줌

변수 sstr에 원하는 데이터를 넣어줌. 이때 원하는 데이터는 책목록 40개이기 때문에 idx변수를 이용하여 문자열을 변경

변수 ts에 조건에 맞는 태그를 한개 가져옴

ts에 텍스트값 출력


MongoDB

https://www.mongodb.com/home

 

MongoDB: The Developer Data Platform

Get your ideas to market faster with a developer data platform built on the leading modern database. MongoDB makes working with data easy.

www.mongodb.com

MongoDB 실행화면

Collection: 비슷한 유형의 데이터들을 모아놓는 하나의 집합

 

MongoDB 조작

https://pymongo.readthedocs.io/en/stable/tutorial.html

 

Tutorial — PyMongo 4.3.3 documentation

Tutorial This tutorial is intended as an introduction to working with MongoDB and PyMongo. Prerequisites Before we start, make sure that you have the PyMongo distribution installed. In the Python shell, the following should run without raising an exception

pymongo.readthedocs.io

MongoDB 4.3.3 튜토리얼 사이트

 

mongo.py
0.00MB

 

1. MongoDB 접속

from pymongo.mongo_client import MongoClient

client = MongoClient('mongodb://localhost:27017/')

2. DB 선택

db = client.local

client에 있는 local DB 사용. 다른 DB를 원한다면 local말고 다른 DB를 선택하면 됨

 

3. Collection 선택

collection = db.startup_log

DB에 있는 Collection 중 startup_log선택. 다른 Collection를 원한다면 startup_log말고 다른 Collection를 선택하면 됨

 

데이터 출력

rows = collection.find()        #반복문을 이용해 안에 데이터를 확인할 수 있음
for row in rows:
    print(row)
row = collection.find_one({'title': "Fastcampus Course!"})
print(row)

반복문을 이용해 안에 데이터를 일일이 확인할 수 있음

find_one에 조건을 주어 원하는 데이터를 확인할 수 있음(Querying)

 

데이터 삽입

collection.insert_one({
    "title": "Fastcampus Course!",
    "Content": "3 Week Course"
})

MongoDB에서 데이터가 삽입된걸 확인할 수 있다

    db['yes24'].insert_one({
        'Title': ts.text
    })

없는 collection도 생성해서 바로 데이터를 삽입할 수 있음

'기초 > 웹 개발 왕초보 입문' 카테고리의 다른 글

3주차_서버 만들기3  (0) 2022.12.21
3주차_서버 만들기  (0) 2022.11.30
2주차_서버와 통신하기 3  (0) 2022.11.30
2주차_서버와 통신하기 2  (0) 2022.11.30
2주차_서버와 통신하기  (0) 2022.11.28

댓글