'파썬'에 해당되는 글 1건

  1. 2022.03.31 python 스토어 가격 가저오기 491
IT2022. 3. 31. 23:08
반응형

1. 태그의 클래스 값만 가져오는 함수.

 

태그의 지정된 클래스 값을 가져오는 함수를 만들어 보겠습니다.

from urllib.request import urlopen
from bs4 import BeautifulSoup

웹 크롤링을 위해 가장 기본이 되는 라이브러리를 불러오겠습니다. 간략하게 설명하면 urlopen은 url 페이지의 html 코드를 가져오는 라이브러리이고 BeautifulSoup는 html 문서를 파싱해 데이터를 쉽게 가져올 수 있도록 도와주는 라이브러리입니다.

def getClassValue(url, tag, className) :
    html = urlopen(url)
    bsObject = BeautifulSoup(html, "html.parser")
    content = bsObject.body.find(tag,{"class", className})
    return content.text  

getClassValue는 입력된 url을 urlopen으로 html 소스를 가져온 뒤 BeautifulSoup로 파싱 합니다. 파싱 된 데이터에서 입력된 tag와 className을 찾고 마지막에 해당 태그에 있는 value값을 리턴하는 함수입니다.

 

find를 쓰게 되면 1개 항목만 가져오게 됩니다. 혹시 모든 항목을 검색하고 싶다면 find_all로 변경하면 되고 배열로 값을 받을 수 있습니다.

 

2. 네이버 스토어 상품명 가져오기

 

url_list = [
    "https://smartstore.naver.com/soommask/products/4828127993",
    "https://smartstore.naver.com/aseado/products/4837257765",
    "https://smartstore.naver.com/aseado/products/4837266971",
    "https://smartstore.naver.com/aseado/products/3765693172",
    "https://smartstore.naver.com/aer-shop/products/4722827602",
    "https://smartstore.naver.com/aer-shop/products/4722827602",
    "https://smartstore.naver.com/korea-mask/products/4825762296",
    "https://m.smartstore.naver.com/ygfac/products/3905641271",
    "https://smartstore.naver.com/gonggami/products/4705579501"
];

상품명을 가져오기 위한 주소를 배열에 담아줍니다.

titles = []

tag = 'strong'
className = 'title_simplebuy'

for url in url_list :
    titles.append(getClassValue(url, tag, className))    

검색할 태그와 클리스 이름을 정의하고 for문으로 배열에 있는 데이터들을 실행하며 title을 수집합니다.

print(titles)

위와 같이 출력되는 것을 볼 수 있습니다.

 

3. 가격 가져오기

 

제목처럼 이제 가격을 가져오겠습니다.

위에선 이미 태그를 분석하여 상품명이 있는 태그와 클래스를 알았기 때문에 한 번에 가져올 수 있었습니다.

이번에는 어떤 태그에 가격이 있을지 확인하여 가져오는 방법을 정리하겠습니다.

html= urlopen("https://smartstore.naver.com/sangkong/products/4762917002")
bsObject = BeautifulSoup(html, "html.parser")
bsObject

BeautifulSoup로 파싱 한 데이터를 출력해 보면 위와 같이 확인할 수 있습니다.

이 요소들 중에 가격이 표시된 부분을 찾아봅시다.

<input name="productSalePrice" type="hidden" value="18000"/>

위 태그에 가격이 있는 것을 발견할 수 있네요

이제 위에서 했던 함수를 응용해서 값을 가져오는 함수를 만들어 보겠습니다.

def getNameValue(url, tag, name) :
    html = urlopen(url)
    bsObject = BeautifulSoup(html, "html.parser")
    content = bsObject.find(tag, {"name": name})
    return content.get('value')  

해당 태그의 value 값을 가져오도록 조금 수정했습니다.

이제 다시 함수를 돌려줄까요?

prices = []

tag1 = 'input'
name = 'productSalePrice'

for url in url_list :
    prices.append(getNameValue(url, tag1, name))
print(prices)

상품마다 가격을 가져오는 것을 확인할 수 있습니다.

반응형
Posted by Dream Come True