귀하의 문
response = HtmlResponse(url=URL)
은 빈 몸, a "local scope" HtmlResponse
object을 구축합니다. 그것은 아무것도 다운로드하지 않으며 특히 http://doc.scrapy.org/en/latest/_static/selectors-sample1.html에있는 리소스가 아닙니다.
일반적으로 사용자가 HtmlResponse
개체를 직접 만들지는 않습니다. 사용자가 부여한 Request
인스턴스 처리가 완료되면 Scrapy 프레임 워크에서 해당 개체를 구성하게합니다. Request(url='http://doc.scrapy.org/en/latest/_static/selectors-sample1.html')
당신이 Scrapy을 시도하는 경우에, 나는 당신이 scrapy shell
놀이 제안 : fetch('http://someurl')
를 사용하여 대화 형 쉘 내부에, 당신은 다운로드를 트리거 할 수 있습니다 (그리고 작업을 "실제"Response
개체를 얻을) :
$ scrapy shell
2016-06-14 10:59:31 [scrapy] INFO: Scrapy 1.1.0 started (bot: scrapybot)
(...)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x7f1a6591d588>
[s] item {}
[s] settings <scrapy.settings.Settings object at 0x7f1a6ce290f0>
[s] Useful shortcuts:
[s] shelp() Shell help (print this help)
[s] fetch(req_or_url) Fetch request (or URL) and update local objects
[s] view(response) View response in a browser
>>> fetch('http://doc.scrapy.org/en/latest/_static/selectors-sample1.html')
2016-06-14 10:59:51 [scrapy] INFO: Spider opened
2016-06-14 10:59:51 [scrapy] DEBUG: Crawled (200) <GET http://doc.scrapy.org/en/latest/_static/selectors-sample1.html> (referer: None)
>>> response.xpath('//title/text()').extract()
['Example website']
- 서브 클래스
scrapy.Spider
,
- 구걸하는 URL을 정의 : 쉘 외부, 실제로 데이터를 다운로드하려면 다음을 수행해야
import scrapy
class TestSpider(scrapy.Spider):
name = 'testspider'
# start_urls is special and internally it builds Request objects for each of the URLs listed
start_urls = ['http://doc.scrapy.org/en/latest/_static/selectors-sample1.html']
def parse(self, response):
yield {
'title': response.xpath('//h1/text()').extract_first()
}
:
- 및 쓰기 콜백 메소드에서 다운로드에서 말하자면,라는 파일에 (그들에게
아주 간단한 예를 전달받을 Response
객체, test.py
내부에 랩, 다운로드 한 데이터에서 작동합니다
다음 거미를 실행해야합니다.Scrapy 실행 단일 파일 거미에 대한 명령이 있습니다
$ scrapy runspider test.py
을 그리고 당신은 콘솔이 얻을 :
2016-06-14 10:48:05 [scrapy] INFO: Scrapy 1.1.0 started (bot: scrapybot)
2016-06-14 10:48:05 [scrapy] INFO: Overridden settings: {}
2016-06-14 10:48:06 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.logstats.LogStats', 'scrapy.extensions.corestats.CoreStats']
2016-06-14 10:48:06 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-06-14 10:48:06 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-06-14 10:48:06 [scrapy] INFO: Enabled item pipelines:
[]
2016-06-14 10:48:06 [scrapy] INFO: Spider opened
2016-06-14 10:48:06 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-06-14 10:48:06 [scrapy] DEBUG: Crawled (200) <GET http://doc.scrapy.org/en/latest/_static/selectors-sample1.html> (referer: None)
2016-06-14 10:48:06 [scrapy] DEBUG: Scraped from <200 http://doc.scrapy.org/en/latest/_static/selectors-sample1.html>
{'title': 'Example website'}
2016-06-14 10:48:06 [scrapy] INFO: Closing spider (finished)
2016-06-14 10:48:06 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 252,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 501,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2016, 6, 14, 8, 48, 6, 564591),
'item_scraped_count': 1,
'log_count/DEBUG': 2,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'start_time': datetime.datetime(2016, 6, 14, 8, 48, 6, 85693)}
2016-06-14 10:48:06 [scrapy] INFO: Spider closed (finished)
당신이 정말로 실제로 웹 데이터를 다운로드하지 않고, 선택기로 재생하려면이, 가정 당신은, 당신이 할 수 있습니다 (브라우저에서 view-source:
에서 예를 복사에 대한) 이미 로컬 데이터가 있지만 몸 제공해야합니다 :
>>> response = HtmlResponse(url=URL, body='''
... <!DOCTYPE html>
... <html>
... <head>
... </head>
... <body>
... <h1>Herman Melville - Moby-Dick</h1>
...
... <div>
... <p>
... Availing himself of the mild, summer-cool weather that now reigned in these latitudes, ... them a care-killing competency.
... </p>
... </div>
... </body>
... </html>''', encoding='utf8')
>>> response.xpath('//h1')
[<Selector xpath='//h1' data='<h1>Herman Melville - Moby-Dick</h1>'>]
>>> response.xpath('//h1').extract()
['<h1>Herman Melville - Moby-Dick</h1>']
>>>
당신이 오 scrapy을 최대한 활용하기를 튜토리얼을 따라하면 응답 객체가 요청에서 요청으로 자동 생성됩니다. –