📌 Python Scraping과 crawling

  • crawling 모듈
    - requests : 접속할 url에 접근하여 정보를 가져오는 모듈
    - BeautifulSoup : requests로 가져온 정보를 parsing하는 역할
data = requests.get("https://beomi.github.io/beomi.github.io_old/")
soup = BeautifulSoup(data.text, 'html.parser')

links = []
for mother in soup.find_all("h3"):
    links.append("https://beomi.github.io"+mother.find("a")["href"])
if links:
    return links


📌 Python scraping 병렬 처리

  • Pool 모듈 사용
    - Pool 모듈 : multiprocessing을 가능하게 하는 병렬처리 지원 모듈
import requests
from bs4 import BeautifulSoup
import time
from multiprocessing import Pool

def get_links():    # a tag의 주소 읽기
    data = requests.get("https://beomi.github.io/beomi.github.io_old/")
    soup = BeautifulSoup(data.text, 'html.parser')

    links = []
    for mother in soup.find_all("h3"):
        links.append("https://beomi.github.io"+mother.find("a")["href"])
    if links:
        return links

def get_content(link):  # a tag에 의한 해당 사이트 문서 내용 중 일부 문자값 읽기
    req = requests.get(link)
    soup = BeautifulSoup(req.text, 'html.parser')
    str = soup.find("h1").text
    return str

if __name__ == '__main__':
    startTime = time.time()
    pool = Pool(processes=3)
    print(pool.map(get_content, get_links()))
    endTime = time.time()
    print(f'총 시간 : {endTime-startTime}')


📌 Python 정적 Web Server 구동

  • Web Server 모듈
    - SimpleHTTPRequestHandler : client의 요청과 그에 대한 server의 응답만 가능한 서버 핸들러 모듈
    - HTTPServer : 기본적인 소켓 연결을 관리하는 모듈

  • 서버 구성
from http.server import SimpleHTTPRequestHandler, HTTPServer
# HTTPServer : 기본적인 소켓 연결을 관리한다.
# SimpleHTTPRequestHandler : 요청 처리(get, post)

port = 7777

handler = SimpleHTTPRequestHandler
serv = HTTPServer(('127.0.0.1', port), handler)

print('웹 서비스 시작')
serv.serve_forever()


📌 Python 동적 Web Server

  • Web Server 모듈
    - CGIHTTPRequestHandler : 양방향 통신 기반의 동적 웹서버 운영이 가능한 모듈

  • CGI란?
    - Common Gate Interface
    - 웹서버와 외부 프로그램 사이에서 정보를 주고받는 양방향 통신 규약

  • 서버 구성
from http.server import CGIHTTPRequestHandler, HTTPServer

port = 8888
class Handler(CGIHTTPRequestHandler):
    cg_directories = ['/cgi-bin']

serv = HTTPServer(('127.0.0.1', port), Handler)
print('웹 서버 시작')
serv.serve_forever()


profile
데이터 사이언티스트를 목표로 하는 개발자

0개의 댓글