웹 스크래핑

김찬울·2021년 7월 13일
0

웹 스크래핑에 대해 알아보자.

웹크롤링과는 다르게 스크래핑은 미리 가져온 정보를 뜯어내는 느낌으로 웹사이트에서 가져온 정보를 가공하여 원하는 정보만 가져오는 것을 말한다.
이를 통해 정보를 손쉽게 가져와서 편집할 수 있다.

requests, BeautifulSoup

이를 사용하기위해 두가지의 모듈을 주로 사용한다.

requests는 url을 받아오는 역할이고 BeautifulSoup는 받아온 url의 내용을 사용자가 다루기 편하게 도와준다.

그렇게 받아온 url의 내용은 해당 웹 사이트를 구성하는 html, css, javascript의 조합으로 이루어져 있는데 웹에서 가져오는 것들은 대부분 html에서도 body의 내용이다.

어떤 것을 할 수 있냐면 쇼핑사이트에서 쇼핑목록을 추출하고 원하는 평점이나 리뷰수에 만족하는 것들만 따로 출력하게끔 조건을 직접 부여할 수 있게된다.

이런 편리함은 데이터가 커지면 커질수록 효율성을 발휘한다.

import requests
from bs4  import BeautifulSoup

for i in range(1, 6):
    url1 = "https://www.coupang.com/np/search?q=%EB%85%B8%ED%8A%B8%EB%B6%81&channel=user&component=&eventCategory=SRP&trcid=&traid=&sorter=scoreDesc&minPrice=&maxPrice=&priceRange=&filterType=&listSize=36&filter=&isPriceRange=false&brand=&offerCondition=&rating=0&page="
    url2 = "&rocketAll=false&searchIndexingToken=1=4&backgroundColor="
    url = url1+str(i)+url2
    headers = {'user-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
    res = requests.get(url, headers = headers)

    soup = BeautifulSoup(res.text, 'lxml')
    products = soup.find_all('li' , {'class' : 'search-product'})
    for product in products:
        title = product.find('div', {'class' : 'name'})
        if '삼성' not in title.text:
            continue
        price = product.find('strong', {'class' : 'price-value'})
        star = product.find('em', {'class': 'rating'})
        review = product.find('span', {'class': 'rating-total-count'})
        ur = product.find('a')
        ur = ur['href']
        ad = product.find('span', {'class' : 'ad-badge-text'})
        if ad:
            continue
        if (star and review and int(review.text[1:-1]) >= 100 and float(star.text) >= 4.5):
            print(f'{title.text} \n가격: {price.text}, 평점: {star.text}, 리뷰수: {review.text}\n 링크 : https://www.coupang.com{ur}\n', '*' * 50)

해당 코드는 강의시간에 직접 작성한 코드인데
쇼핑몰 사이트에서 노트북이라는 검색어에 대한 결과를

평점 4.5이상 리뷰수 100이상이며 광고가 아닌 삼성제품들만 가져오는 코드이다.

이처럼 몇 줄 되지 않는 코드들로만 가지고 5페이지가 넘는 사이트를 간단하게 정리할 수 있다.

headers

웹에서 쓰이는 헤더는 다른 의미를 가진다.
해당 헤더는 간단하게 사용자 속성이라고 생각하면 편하다.
우리는 매번 다른 디바이스로 웹서핑을 하는데
우리가 어떤 디바이스로 어떤 os로 어떤 환경으로 웹환경에 접속하느냐에 따라서 사용자가 보는 방식

이 다르기 때문에 최근의 웹페이지에서는 이 헤더에 따라서 사이트를 다르게 출력한다.

User agent string

이를 검색하여 what is my user agent 사이트를 들어가면 자신에게 맞는 user agent를 제공한다.

profile
코린코린이

0개의 댓글

관련 채용 정보