•
best 상품 데이터 40개 수집
•
상품 이미지 40개 수집
1. URL
url = 'https://www.celltrionbeauty.com/main/best-items'
Python
복사
2. request > response : html(str)
response = requests.get(url)
Python
복사
3. html(str) > beautifulsoup obj : css selector > dataframe
•
태그 안 속성값에 접근할 때 : select_one(태그이름).get(속성이름)
bs = BeautifulSoup(response.text, 'html.parser')
selector = '#productListBody > div'
elements = bs.select(selector)
len(elements) # 40
Python
복사
# 원하는 정보(제목, 가격, image) 가져오기
element = elements[0]
data = {
'title' : element.select_one('.tit').text,
'price' : element.select_one('.pri').text,
'img' : element.select_one('imp').get('data-src')
}
Python
복사
# parsing all elements
items = []
for element in elements:
data = {
'title' : element.select_one('.tit').text,
'price' : element.select_one('.pri').text,
'img' : element.select_one('imp').get('data-src')
}
items.append(data)
df = pd.DataFrame(items)
df.tail(2)
Python
복사
title | price | img | |
38 | 누디씬 물온 립밤 3g | 7,900원 | https://image.celltrionbeauty.com/attach/item/... |
39 | [기획세트]플라센타 단백질 수분 앰플 50ml x 3병+미스트 1병+마스크팩 10장 | 89,900원 | https://image.celltrionbeauty.com/attach/item/... |
4. Download images
파이썬에서 이미지 파일과 관련해 전처리, 흑백변환, 사이즈 조절, 출력 등의 작업을 수행하려면 PIL 패키지를 사용해야 한다.
import os
from PIL import Image as pil
Python
복사
# 현 작업디렉토리에 이미지 파일을 저장할 디렉토리(폴더) 생성
path = 'CrawlingImage'
os.makedirs(path, exist_ok=True) # CrawlingImage라는 폴더 생성
os.listdir()
Python
복사
['.ipynb_checkpoints',
'.virtual_documents',
'01_requests_naver_stock.ipynb',
'02_requests_daum_exchange.ipynb',
'03_rest_api.ipynb',
'04_requests_zigbang.ipynb',
'05_html.ipynb',
'06_css_selector.ipynb',
'07_celltrion_beauty_mall.ipynb',
'07_naver_relational_keywords.ipynb',
'08_naver_stock_report_code.ipynb',
'Class.ipynb',
'CrawlingImage']
Plain Text
복사
# 이미지 다운로드
img_link = df.loc[0, 'img']
filename = 'test'
filelink = f'{path}/{filename}.jpg' # 이미지 파일 path 설정
response = requests.get(link) # 이미지 link 페이지 요청 -> 응답
with open(filelink, 'wb') as file:
file.write(response.content) # 응답받은 데이터 정보(text 아님, content) 파일에 입력
os.listdir(path) # CrawlingImage 폴더에 있는 파일 정보 확인
Python
복사
['test.jpg']
# 파이썬에서 로컬 이미지 파일 열기
pil.open(filelink)
Python
복사