본문 바로가기
카테고리 없음

request로 웹크롤링

by 스꼬맹이브로 2021. 6. 9.
728x90
반응형
SMALL

저번에 selenium으로 웹크롤링하는 코드를 올렸었는데, request로 크롤링이 더 빠르다고 해서

같은 코드를 다른 방식으로 한번 수정해보았다.

이전내용은 여기에!

https://yuna96.tistory.com/66

 

selenium으로 웹 크롤링

실시간으로 올라오는 데이터를 수집하기 위해 크롤링을 시작하기로..! 언어는 python을 사용했고 여러 개의 창으로 나뉘어 있어 반복해서 수집하되, 30초 간격으로 수집을 수행하였다. from selenium i

yuna96.tistory.com

수정하면서 살짝 바뀐 부분이 있을 수 있으므로 그 부분은 유의바람!

 

import csv
import requests
from bs4 import BeautifulSoup
import datetime
import urllib3
urllib3.disable_warnings()

# 카테고리 별 상세 주소 값(example)
page = ['A', 'B', 'C', 'D', 'E', 'F']

# 카테고리 별 이름(example)
pageName = ['A', 'B', 'C', 'D', 'E', 'F']

# 저장할 경로
file_path_1 = '경로 지정'

get_url_others = '홈페이지 주소 지정'

def other_crowling():
    for i in range(len(page)):
        f1 = open(file_path_1.format(pageName[i]), 'r', encoding='cp949')
        line = f1.readlines()
        lines = list(map(lambda s: s.strip(), line))
        line = [v for v in lines if v]
        if line != '\n':
            line = line[-1].split(",", 4)
        f1 = open(file_path_1.format(pageName[i]), 'a', encoding='cp949', newline="\n")
        csvWriter = csv.writer(f1)
        req = requests.get(get_url_others.format(page[i]), verify=False)
        html = req.text
        soup = BeautifulSoup(html, 'html.parser')
        try:
        	#'box'로 되어있는 클래스를 가져오기 위해 지정
            cl = soup.find('div', class_="box").get_text().strip().split("\n")
            #알맞게 바꿔주기
            for c in range(len(cl)):
                cl[c] = cl[c].strip()
                cl[c] = cl[c].replace('\t', '')
                cl[c] = cl[c].replace('\r', '')
                if cl[c] == "<" or cl[c] == ">":
                    cl[c] = ""
            cl = [v for v in cl if v]
            cllist = list(filter(None, cl))
            line[4] = line[4].replace("\"", "")
            if line != cllist:
                csvWriter.writerow(cllist)
        except:
            print(pageName[i] + " except발생 ")
            print(datetime.datetime.now())
        f1.close()

#크롤링 함수 실행
while(True):
	other_crowling()
728x90
반응형
LIST