본문 바로가기

Python/Crawler

PYTHON 크롤링을 이용한 만개의 레시피 크롤링 - 1

크롤링 공부를 하면서 항상 숙지해야 할 점이 크롤링 하는 것은 자유지만 타인의 콘텐츠를 무단으로 사용하면 안된다는 것이다.

상업적인 용도로 사용할 때에는 저작권자의 허락을 받아야 한다.

안그러면 철컹철컹






레시피를 제공하는 사이트로 만개의 레시피(http://www.10000recipe.com/)라는 곳이 있다.

이 사이트를 크롤링 해본다.



0. 주소 분석


기본 주소 : http://www.10000recipe.com/

검색 주소 : http://www.10000recipe.com/recipe/list.html?q=샌드위치&order=reco&page=1


보면 알겠지만 아주 단순하다.


검색 주소 : http://www.10000recipe.com/recipe/list.html?q=<검색 단어>&order=reco&page=<페이지 번호>


1. 먼저 한 페이지를 크롤링 해본다.


크롤링 하고 싶은 페이지를 먼저 정한다.


나는 샌드위치를 좋아하기 때문에 추천순 넘버 원인 또띠아 랩 샌드위치를 선택했다.


http://www.10000recipe.com/recipe/6900135


구성을 크게 4가지로 나누었다.

제목 + 재료 + 요리 순서 + 해시태그



순서대로 제목 - 재료 - 순서 - 태그다.
개미도 아니고 맨날 이렇게 분석해야 한다는 것이 조금 화나지만 그래야 크롤링 하기 편하다.

훌륭한 레시피를 제공해주는 분의 블로그는
https://m.blog.naver.com/PostList.nhn?blogId=96may0504&proxyReferer=http:%2F%2Fwww.10000recipe.com%2Frecipe%2F6900135
이 주소로 들어가면 된다.


def PageCrawler(recipeUrl):
	url = 'http://www.10000recipe.com/' + recipeUrl

	req = urllib.request.Request(url)
	sourcecode = urllib.request.urlopen(url).read()
	soup = BeautifulSoup(sourcecode, "html.parser")
	
	recipe_title = [] #레시피 제목
	recipe_source = {} #레시피 재료
	recipe_step = [] #레시피 순서
	recipe_tag = [] #레시피 해시태그
	
	res = soup.find('div','view2_summary')
	res = res.find('h3')
	recipe_title.append(res.get_text())
	res = soup.find('div','view2_summary_info')
	recipe_title.append(res.get_text().replace('\n',''))

	res = soup.find('div','ready_ingre3')

	#재료 찾는 for문 가끔 형식에 맞지 않는 레시피들이 있어 try / except 해준다.
	try :
		for n in res.find_all('ul'):
			source = []
			title = n.find('b').get_text()
			recipe_source[title] = ''
			for tmp in n.find_all('li'):
				source.append(tmp.get_text().replace('\n','').replace(' ',''))
			recipe_source[title] = source
	except (AttributeError):
			return

	#요리 순서 찾는 for문
	res = soup.find('div','view_step')
	i = 0
	for n in res.find_all('div','view_step_cont'):
		i = i + 1
		recipe_step.append('#' + str(i) + ' ' + n.get_text().replace('\n',' '))
		#나중에 순서를 구분해주기 위해 숫자와 #을 넣는다.
	
	#해시태그가 글 내에 있는지 판단하고 출력해주는 for문
	if (res.find('div','view_tag')):
		recipe_tag = res.find('div','view_tag').get_text()
		#del recipe_tag[0]
		
	#블로그 형식의 글은 스텝이 정확하게 되어있지 않기 때문에 제외해준다
	if not recipe_step:
		return
	
	recipe_all = [recipe_title, recipe_source, recipe_step, recipe_tag]
	return(recipe_all)

실행해보면 다음과 같은 결과가 나타난다.



데이터의 정리가 모호한데, 나머진 전부 리스트로 처리하였지만 재료 부분은 딕셔너리로 넣어주었다.

나중에 키값만 따로 가공할 수도 있기 때문이다.