일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- 미국주식
- intelliJ plugin
- JDK1.3
- IntelliJ
- Vue
- Vue 강의
- 젠킨스
- 애드센스 수익
- docker 명령어
- 구글 애드센스 수익
- spring boot 시작
- 도커
- docker mysql
- docker
- 미국 배당주
- 티스토리 광고 수익
- Spring
- gradle
- spring Annotation
- Vue 알아보기
- Python 기본편
- scrapy
- Spring Batch
- apache log4j
- python 기초
- MYSQL
- Vue 배우기
- AES256
- python
- Spring Batch 강의
나만의공간
Scrapy 가이드 #2 본문
Scrapy 가이드 #1에서는 Scrapy Project 생성 및 Spider를 만들어 크롤링 하는 방법 까지 설명이 되어 있다.
이번장은 계속 이어서 크롤링한 웹페이지에서 내가 원하는 데이타를 Items에 추출하는 내용을 설명한다.
1. Extracting Items (아이템 추출)
1) Selectors에 대한 소개
(1) 크롤링한 웹 페이지에서 데이타를 추출하는 몇가지 방법이 있다.
XPath 혹은 CSS 표현을 이용한 Selectors를 이용하거나
더 많은 정보가 필요할 경우 Selectors Documeneation을 참조하기 바란다.
(2) XPath 표현을 이용한 샘플
▶ /html/head/title : title elements를 선택한다. HTML문서중 head에 있는 정보이다.
▶ /html/head/title/text() : title elements에 대한 text내용을 가져온다.
▶ //td : td elements를 선택한다.
▶ //div[@class="mime"] : div elements에서 class="mime"속성을 가진 모든 것을 선택한다.
(3) Spider에 xpath를 추가한 내용
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def parse(self, response):
for sel in response.xpath('//ul/li'):
title = sel.xpath('a/text()').extract()
link = sel.xpath('a/@href').extract()
desc = sel.xpath('text()').extract()
print title, link, desc
(4) 이제 본격적으로 items 클래스에 Response내용을 집어 넣어 보자
import scrapy
from tutorial.items import DmozItem
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def parse(self, response):
for sel in response.xpath('//ul/li'):
item = DmozItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('text()').extract()
yield item
(5) Python diectory Web 페이지에 대한 크롤링 예제
import scrapy
from tutorial.items import DmozItem
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/",
]
def parse(self, response):
for href in response.css("ul.directory.dir-col > li > a::attr('href')"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback=self.parse_dir_contents)
def parse_dir_contents(self, response):
for sel in response.xpath('//ul/li'):
item = DmozItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('text()').extract()
yield item
(6) 크롤링 한 데이타를 파일로 저장하는 법
scrapy crawl dmoz -o items.json
(7) setting.py 파일에 pipeline 파일 환경정보를 변경한다.
# Scrapy settings for dirbot project
SPIDER_MODULES = ['dirbot.spiders']
NEWSPIDER_MODULE = 'dirbot.spiders'
DEFAULT_ITEM_CLASS = 'dirbot.items.Website'
ITEM_PIPELINES = {'dirbot.pipelines.JsonLinesPipeline': 1} #pipeline에서 사용하는 클래스 명을 기재 한다.
(8) 크롤링한 파일을 Pipeline을 이용하여 정제 및 파일로 저장하는 방법 (Json)
pipelines.py에 아래 내용으로 변경한다.
from scrapy import signals
from scrapy.exporters import JsonLinesItemExporter
class JsonLinesPipeline(object):
def __init__(self):
self.files = {}
@classmethod
def from_crawler(cls,crawler):
pipeline = cls()
crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
return pipeline
def spider_opened(self,spider):
file = open('%s_products.json'% spider.name,'w+b')
self.files[spider] = file
self.exporter = JsonLinesItemExporter(file)
self.exporter.start_exporting()
def spider_closed(self, spider):
self.exporter.finish_exporting()
file = self.files.pop(spider)
file.close()
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
위와 같이 세팅 후 "scrapy crawl dmoz"을 커맨드에 입력 후 실행하면 Json 파일 (dmoz_products.json)이 하나 생성된다.
'IT > Python' 카테고리의 다른 글
Python 기본편 (설치) #1 (0) | 2024.01.08 |
---|---|
Scrapy 가이드 #3 (MongoDB 사용하기) (0) | 2016.05.30 |
Scrapy 가이드 #1 (0) | 2016.05.26 |
Python whl 파일 설치 방법 (0) | 2016.05.23 |
Python을 이용한 웹 크롤링 개발 도구 선택 (0) | 2016.05.23 |