Scrapyまとめ
3637 ワード
インストールおよび環境の必要性
まずmac、python環境pip install Scrapyを構築しました
期間中に必要とされるのは、Scrapy is written in pure Python and depends on a few key Python packages(among others):
基本テストの使用
response.css('title') response.css('title::text').extract() response.css('title').extract() response.css('title::text').extract_first() response.css('title::text')[0].extract() response.css('title::text').re(r'Quotes.*') response.css('title::text').re(r'Q\w+') response.css('title::text').re(r′(w+)to(w+)′)xPathによりresponseを抽出する.xpath('//title') response.xpath('//title/text()').extract_first()
プログラム内の抽出demo
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('small.author::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
}
抽出結果の保存
scrapy crawl quotes -o quotes.JSON Lines scrapy crawl quotes-o quotesとして保存jl抽出リンクresponse.css('li.next a').extract_first() response.css('li.next a::attr(href)').extract_first()
Demo
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://quotes.toscrape.com/page/1/',
]
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').extract_first(),
'author': quote.css('small.author::text').extract_first(),
'tags': quote.css('div.tags a.tag::text').extract(),
}
next_page = response.css('li.next a::attr(href)').extract_first()
if next_page is not None:
next_page = response.urljoin(next_page)
yield scrapy.Request(next_page, callback=self.parse)
パラメータ付き抽出コマンド
scrapy crawl quotes -o quotes-humor.json-a tag=humorフォーマット出力json scrapy runspider quotes_spider.py -o quotes.json