Python 일반 python Scrapy 사용법

2014.12.11 09:19

졸리운_곰 조회 수:2163




python Scrapy (crawling)



crawling.....말이 크롤링이지 그냥 웹페이지를 긁어오기다 콜록.. ㅋㅋ 나는 python을 좋아한다. 훌륭한 개발자분들이 편리한 모듈, 프레임워크등을 많이 만들어 놓으셨다. 감사합니다^^

Crawling 하는 방법은 엄청 많다. 그중에서 나는 Scrapy를 사용했다...스크랩파이? 콜록 ㅋㅋ 사용법은 매우 간단하다. Scrapy Tutorial 튜토리얼도 매우 친절하게 나와있다.

당연히....python이 필요하다 ㅋㅋㅋ 2.6 또는 2.7버전이 필요하다. 3.0은 안해 봣지만 안됄지 쉽다..콜록 ㅋㅋ pip 나 easy_install을 이용하여 편하게 이지 인스톨한다..콜록

[출처] http://semicolok.blogspot.de/2013/09/python-scrapy-crawling.html


1easy_install Scrapy
1pip install Scrapy
설치가 끝낫다....필요한 디펜던시들은 알아서 처리해준다...편하다 콜록...ㅋㅋ

scrapy 프로젝트를 생성한다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

1scrapy startproject tutorial
scrapy.cfg: 프로젝트의 설정 파일 tutorial/: 프로젝트 폴더 tutorial/items.py: 사용할 item, 뽑아낼 데이터가 들어 갈 것이다. tutorial/pipelines.py: 뽑아낸 데이터로 뭔가 처리할때 쓴다. 뭔가..ㅎ tutorial/settings.py: 프로젝트 설정 파일 tutorial/spiders/: 정보를 모아줄 거미들...ㅋㅋ동작할 크롤러들이다.

item.py에 사용할 item을 추가한다.

1from scrapy.item import Item, Field
2class HealthItem(Item):
3 name = Field()
4 phone = Field()
5 address = Field()
6 home_page = Field()
spiders폴더에 정보를 모아 줄 거미를 추가한다..ㅎㅎ
01from scrapy.spider import BaseSpider
02from scrapy.selector import HtmlXPathSelector
03 
04from vwell.items import HealthItem
05 
06class HealthSpider(BaseSpider):
07    # spider 이름 유니크해야한다.
08    name = "health"
09    allowed_domains = ["cdc.go.kr"]
10    # 크롤링할 url
11    start_urls = [
13    ]
14     
15    # 데이터 파싱
16    def parse(self, response):
17  hxs = HtmlXPathSelector(response)
18  healths = hxs.select('//*[@id="contents"]/div[@class="conbox sch"]/div[@class="tableA"]/table/tbody/tr')
19  items = []
20  count = 0
21 
22  for health in healths:
23   item = HealthItem()
24   item['name'] = health.select('//td')[count*4].select('text()').extract()[0]
25   item['phone'] = health.select('//td')[count*4+1].select('ul/li')[0].select('text()').extract()
26   item['phone'].append(health.select('//td')[count*4+1].select('ul/li')[1].select('text()').extract()[0])
27   item['address'] = health.select('//td')[count*4+2].select('text()').extract()[0]
28   item['home_page'] = health.select('//td')[count*4+3].select('a/@href').extract()[0]
29   count += 1
30   items.append(item)
31 
32  return items
HtmlXPathSelector의 select를 이용해 html을 파싱한다. 사용법은 금방 적응 할 정도로 간단하다. tag이름과 / 로 태그를 선택할 수있다.
1hxs.select('//ul/li')
@를 이용하여 태그의 properties에 접근할 수있다.
1hxs.select('//*[@id="contents"]/div[@class="conbox sch"]/div[@class="tableA"]/table/tbody/tr')
text()로 value값을 가져 올 수 있다. extract()를 할때 List로 반환 된다는데 주의하자.
1hxs.select('//ul/li/text()').extract()
scrapy.cfg 파일있는 폴더로가서 실행해보자.
1scrapy crawl health -o items.json -t json
크롤링한 결과는 items.json 파일에 저장되어있을 것이다.

크롤링한 데이터로 다른 처리를 추가하고 싶다면 pipeline을 이용하면된다. pipelines.py파일에 처리할 클래스를 추가하고 settings.py등록해주면 끝이다. 간단하다. 나는 유니코드가 보기 싫어서 스트링으로 저장하는 pipeline을 추가햇다.

01class JsonWriterPipeline(object):
02 
03 def __init__(self):
04  self.file = open('healthList.json', 'w')
05 
06 def process_item(self, item, spider):
07  newItem = {}
08  newItem['name'] = item['name'].encode('utf-8')
09  newItem['phone'] = item['phone']
10  newItem['address'] = item['address'].encode('utf-8')
11  newItem['home_page'] = item['home_page'].encode('utf-8')
12 
13  line =  '{ "name" : "%s", "phone" : ["%s", "%s"], "address" : "%s", "home_page" : "%s" },' %(newItem['name'], newItem['phone'][0].encode('utf-8'), newItem['phone'][1].encode('utf-8'), newItem['address'], newItem['home_page']) + '\n'
14  self.file.write(line)
15  return item
settings.py에 등록해준다.
1ITEM_PIPELINES = [
2    'vwell.pipelines.JsonWriterPipeline'
3]
다시 실행한다. 끝~ 웹페이지 크롤링....쉽다...콜록^^
source : https://github.com/semicolok/python-scrapy



[출처] http://semicolok.blogspot.de/2013/09/python-scrapy-crawling.html






본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
37 윈도우에서 easy_install, pip 사용하기. 졸리운_곰 2015.11.24 1450
36 윈도우에서 파이썬 설치하기 (virtualenv, pip 사용법) file 졸리운_곰 2015.11.24 707
35 How to parse JSON string in Python 졸리운_곰 2015.11.10 451
34 windows 에서 python 2.x 와 3.x 동시 설치 사용하기 졸리운_곰 2015.09.17 628
33 Title: HTML Scraper using pyhton 졸리운_곰 2015.09.01 400
32 기계 학습의 A to Z : 인구 변화 시각화와 예측 file 졸리운_곰 2015.05.21 1736
31 기계 학습의 A to Z : scikit-learn을 활용한 기계 학습(문서 분류) file 졸리운_곰 2015.05.21 2402
30 기계 학습의 A to Z : IPython notebook과 scikit-learn을 활용한 기계 학습 file 졸리운_곰 2015.05.21 2006
29 기계 학습의 A to Z : scikit-learn을 활용한 기계 학습 (군집화, Clustering) file 졸리운_곰 2015.05.21 2084
28 기계 학습의 A to Z : scikit-learn을 활용한 기계 학습 (차원 축소) file 졸리운_곰 2015.05.21 2182
27 기계 학습의 A to Z : scikit-learn을 활용한 기계 학습(모델 평가) [1] file 졸리운_곰 2015.05.21 1411
26 Tkinter로 하는 GUI 프로그래밍 file 졸리운_곰 2015.05.12 1628
25 위대한 LG SMART SMA LG 빅데이터 플랫폼 [파이썬 웹 크롤러] 웹 스파이더 file 졸리운_곰 2015.05.02 1154
24 위대한 LG SMART SMA LG 빅데이터 플랫폼 [소셜 웹 마이닝] 데이터 마이닝, 웹 마이닝 file 졸리운_곰 2015.05.02 775
23 Python CGI Programming file 졸리운_곰 2015.04.28 756
22 파이썬(Python)으로 CGI 프로그램 작성하기 졸리운_곰 2015.04.28 1403
21 winglet: 간단한 web crawler 졸리운_곰 2015.04.08 1748
20 python scrapy 예제, [python] Scrapy - 네이버 영화 파싱 졸리운_곰 2014.12.11 1496
» python Scrapy 사용법 졸리운_곰 2014.12.11 2163
18 python 2.X 와 python 3.X 의 tkinter 코드 호환 유지 기법 : from Tkinter import * 에러시 졸리운_곰 2014.11.03 1767
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED