scrapy startproject myproject
scrapy fetch --nolog --headers http://www.example.com/
scrapy view http://www.example.com/some/page.html
--spider=SPIDER: 跳过自动检测spider并强制使用特定的spider --a NAME=VALUE: 设置spider的参数(可能被重复) --callback or -c: spider中用于解析返回(response)的回调函数 --pipelines: 在pipeline中处理item --rules or -r: 使用 CrawlSpider 规则来发现用来解析返回(response)的回调函数 --noitems: 不显示爬取到的item --nolinks: 不显示提取到的连接 --nocolour: 避免使用pygments对输出着色 --depth or -d: 指定跟进连接请求的层次数(默认: 1) --verbose or -v: 显示每一个请求的详细信息 scrapy parse http://www.example.com/ -c parse_item
scrapy genspider [-t template] <name> <domain> scrapy genspider -t basic example example.com
body = '<html><body><span>good</span></body></html>' Selector(text=body).xpath('//span/text()').extract() response = HtmlResponse(url='http://example.com', body=body) Selector(response=response).xpath('//span/text()').extract()
Scrapy提供了两个实用的快捷方式: response.xpath() 及 response.css()css
>>> response.xpath('//base/@href').extract() >>> response.css('base::attr(href)').extract() >>> response.xpath('//a[contains(@href, "image")]/@href').extract() >>> response.css('a[href*=image]::attr(href)').extract() >>> response.xpath('//a[contains(@href, "image")]/img/@src').extract() >>> response.css('a[href*=image] img::attr(src)').extract()
选择器方法( .xpath() or .css() )返回相同类型的选择器列表,所以你也能够对这些选择器调用选择器方法。下面是一个例子:html
links = response.xpath('//a[contains(@href, "image")]') for index, link in enumerate(links): args = (index, link.xpath('@href').extract(), link.xpath('img/@src').extract()) print 'Link number %d points to url %s and image %s' % args
Selector 也有一个 .re() 方法,用来经过正则表达式来提取数据。然而,不一样于使用 .xpath() 或者 .css() 方法, .re() 方法返回unicode字符串的列表。因此你没法构造嵌套式的 .re() 调用。node
>>> response.xpath('//a[contains(@href, "image")]/text()').re(r'Name:\s*(.*)')
>>> for p in divs.xpath('//p'): # this is wrong - gets all <p> from the whole document ... print p.extract() >>> for p in divs.xpath('.//p'): # extracts all <p> inside ... print p.extract() >>> for p in divs.xpath('p'): #gets all <p> from the whole document ... print p.extract()
例如在XPath的 starts-with() 或 contains() 没法知足需求时, test() 函数能够很是有用。python
>>> sel.xpath('//li//@href').extract() >>> sel.xpath('//li[re:test(@class, "item-\d$")]//@href').extract()
def parse(self, response): l = ItemLoader(item=Product(), response=response) l.add_xpath('name', '//div[@class="product_name"]') l.add_xpath('name', '//div[@class="product_title"]') l.add_xpath('price', '//p[@id="price"]') l.add_css('stock', 'p#stock]') l.add_value('last_updated', 'today') # you can also use literal values return l.load_item()
每一个item pipeline组件都须要调用该方法,这个方法必须返回一个 Item (或任何继承类)对象, 或是抛出 DropItem 异常,被丢弃的item将不会被以后的pipeline组件所处理。
参数:react
import pymongo class MongoPipeline(object): def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.mongo_uri) self.db = self.client[self.mongo_db] def close_spider(self, spider): self.client.close() def process_item(self, item, spider): collection_name = item.__class__.__name__ self.db[collection_name].insert(dict(item)) return item
为了启用一个Item Pipeline组件,你必须将它的类添加到 ITEM_PIPELINES 配置,就像下面这个例子:正则表达式
ITEM_PIPELINES = { 'myproject.pipelines.PricePipeline': 300, 'myproject.pipelines.JsonWriterPipeline': 800, }
分配给每一个类的整型值,肯定了他们运行的顺序,item按数字从低到高的顺序,经过pipeline,一般将这些数字定义在0-1000范围内。mongodb
from twisted.internet import reactor, defer from scrapy.crawler import CrawlerRunner from scrapy.utils.project import get_project_settings runner = CrawlerRunner(get_project_settings()) dfs = set() for domain in ['scrapinghub.com', 'insophia.com']: d = runner.crawl('followall', domain=domain) dfs.add(d) defer.DeferredList(dfs).addBoth(lambda _: reactor.stop()) reactor.run() # the script will block here until all crawling jobs are finished
Scrapyd
Spider中间件
下载器中间件(Downloader Middleware)
内置设定参考手册
Requests and Responses
Scrapy入门教程shell