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






본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
15 [python 데이터분석] [jupyter] 주피터 노트북에 이미지 삽입 file 졸리운_곰 2025.09.06 526
14 [python 데이터분석] [Python] Streamlit 사용법 (python 데이터분석 웹 만들기) file 졸리운_곰 2024.12.22 462
13 [python 데이터분석] Anaconda : Error while loading conda entry point: conda-libmamba-solver (libarchive.so.19: cannot open shared object file: No such file or directory) 졸리운_곰 2024.12.14 520
12 [python 데이터분석] Anaconda | Conda update 반영 안됨(update 후에도 버전 변경 없음) file 졸리운_곰 2024.11.18 431
11 [python 데이터분석] Keeping Anaconda Up To Date 졸리운_곰 2024.05.30 552
10 [python 데이터 분석] 국내 경제 100대 통계지표 졸리운_곰 2024.02.18 672
9 [python 데이터 분석] Python 에서 R언어 패키지 호출 : Calling R From Python With rpy2 file 졸리운_곰 2024.01.28 676
8 [python 데이터 분석] 파이썬을 활용한 코스피, 달러 환율정보 수집부터 차트 시각화까지 file 졸리운_곰 2023.12.11 735
7 [Python 데이터분석][pandas] [Python pandas] DataFrame의 문자열 칼럼을 숫자형으로 바꾸기 : pd.to_numeric(), DataFrame.astype() file 졸리운_곰 2023.12.09 357
6 [Python 데이터분석] [Python 환경설정] VS code 설치 및 Anaconda와 연동하기 file 졸리운_곰 2023.03.17 527
5 [Python 데이터분석][python 데이터분석 프로덕션] [Python] Docker를 사용한 Dash 웹앱 생성 file 졸리운_곰 2021.12.10 403
4 [Python 데이터분석] [pandas] 공공데이터(csv) 활용시 한글 깨짐 현상 해결 file 졸리운_곰 2021.09.30 592
3 [Python 데이터분석] 공공데이터포털::공휴일 데이터 조회 (REST API) file 졸리운_곰 2021.09.30 358
2 [Python 데이터 분석] pandas의 to_csv()를 사용해서 csv 파일로 저장하기(save 하기) 졸리운_곰 2021.09.29 603
1 [Python 데이터 분석] 데이터 과학을 단순하게 만드는 3가지 Python 패키지 file 졸리운_곰 2021.09.24 513
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED