본문 바로가기
1. SW 개발 & IT 트렌드

Python Web Scraping

by soosun 2020. 5. 20.

import requests


def crawl(keyword):
url = "https://search.shopping.naver.com/search/all.nhn?query=?????&cat_id=&frm=NVSHATC"
data = requests.get(url)
print(data.status_code, url)
return data.content
# print(crawl(""))

 

---------------------------------------------------------------------

from bs4 import BeautifulSoup

def getProductInfo(li):
# print(li)
img = li.find("img")
alt = img['alt']

priceReload = li.find("span", {"class":"_price_reload"})
aTit = li.find("a", {"class":"tit"})
href = aTit['href']
print(priceReload)

return {"name":alt, "price":priceReload.text.replace(",", ""), "link":href}

def parse(pageString):
bsObj = BeautifulSoup(pageString, "html.parser")
ul = bsObj.find("ul", {"class":"goods_list"})
lis = ul.findAll("li", {"class":"_itemSection"})

products = []
for li in lis[:1]:
product = getProductInfo(li)
products.append(product)
# try:
# product = getProductInfo(li)
# products.append(product)
# except:
# print("--error--")
return products

 

 

인코딩이 유니코드 인코딩(예: UTF-8 등)이거나 한글 인코딩(예: EUC-KR)이면 일반적으로 한글이 깨지지 않지만, ISO-8859-1와 같이 영문 인코딩이면 한글이 깨지게 된다. 이를 해결하는 방법은 미리 Response 객체의 encoding 을 한글인코딩(예: EUC-KR)이나 None (인코딩 추즉을 하지 않도록) 으로 지정한 후, text 속성을 읽으면 된다. 예를 들어, 아래 예제는 네이버 증권사이트의 ISO-8859-1 인코딩 문제를 처리한 코드이다.

 

import requests

 

resp = requests.get('http://finance.naver.com/')

resp.raise_for_status()

resp.encoding=None   # None 으로 설정

#resp.encoding='euc-kr'  # 한글 인코딩

html = resp.text

print(html)

 

 

# source : https://github.com/Kyeongrok/python_crawler

# source - http://pythonstudy.xyz/

 

예제로 배우는 파이썬 프로그래밍

파이썬 프로그래밍 학습 사이트 파이썬 전자책(eBook) 출간

pythonstudy.xyz

'1. SW 개발 & IT 트렌드' 카테고리의 다른 글

Pillow - Python Imaging Library  (0) 2020.05.20
Matplotlib.org  (0) 2020.05.20
Python 다양한 정규식 패턴 표현  (0) 2020.05.19
Python 표준 라이브러리  (0) 2020.05.17
Python Tip  (0) 2020.05.17

댓글