scrapy源碼https://github.com/scrapy/scrapy/tree/master/scrapy
第一章、scrapy的模塊
有spiders,selector,http,linkextractors,item,loader,exceptions,pipeline等包。
其中,在scrapy的目錄下含有一些快捷的函數,如
scrapy.Spider()(繼承于spiders包),
scrapy.Selector()(繼承于selector包),,
scrapy.Item() (繼承于item包),
scrapy.Request/FormRequest(繼承于http包)。
spiders模塊
常用Rule,CrawlSpider等函數。
一般爬蟲scrapy.spiders.Spider,其他爬蟲都是繼承此爬蟲。
鏈接爬蟲scrapy.spiders.CrawlSpider,
網站爬蟲scrapy.spiders.SitemapSpider
XML源爬蟲scrapy.spiders.XMLFeedSpider
CSV源爬蟲scrapy.spiders.CSVFeedSpider
linkextractors模塊
常用LinkExtractor()函數。
http模塊
常用HtmlResponse()函數
scrapy.http.Request()
scrapy.http.FormRequest()
item模塊
常用Item(),Field()函數
loader模塊
常用ItemLoader函數
exceptions模塊
常用DropItem函數
pipeline
常用image,file包函數
第二章、選擇器 scrapy.selector.Selector(response=None, text=None, type=None)
在scrapy中使用選擇器對response進行解析。如response.xpath()。此時response已經自動被scrapy轉化成了選擇器。選擇器可以由文本或者TextResponse構造形成,如:
from scrapy.http import HtmlResponse```
文本構造
Selector(text=body).xpath('//span/text()').extract()```
TextResponse構造
```response = HtmlResponse(url='http://example.com', body=body)
Selector(response=response).xpath('//span/text()').extract()```
選擇器常用方法xpath()或者css().如sel.xpath(),sel.css()xuan.兩者都返回新的選擇器。
選擇器還有re(),extract(),re_first(),extract_first()方法,前兩個返回字符串列表,后兩個返回字符串列表的第一個字符串。
##xpath
xpath("http://div")會得到文檔所有的div節點構成的選擇器
> ```for p in divs.xpath('.//p'): # extracts all <p> inside
... print p.extract()```
或者
>```for p in divs.xpath('p'): #extracts all <p> inside
print p.extract()```
xpath獲取多個標簽下的文本
> ```sel.xpath("http://div").xpath("string(.)").extract()#返回一個列表,每個元素都是一個div節點下所有的文本。```
獲取指定文本值的元素
>```sel.xpath("http://a[contains(., 'Next Page')]").extract()
sel.xpath("http://a[text()='Next Page']").extract()```
選擇器,在選擇標簽易變的文本時記得用
>```xpath("string(.)")```
在數據項易減少的文本時,用
>```xpath("http://div[contains(text(),'word')]")```
可以利用兄弟父子節點選取。
#第三章、itempipeline
itempipeline是對spider產生的item進行處理。有清洗,驗證,檢查,儲存等功能。itempipeline含有四個方法:
>open_spider(self, spider),
close_spider(self, spider),
from_crawler(cls, crawler),
process_item(self, item, spider).
##不同的item處理
>```if isinstance(item, Aitem):
pass
elif isinstance(item, Bitem):
pass
else:
pass```
##儲存到mongoDB
在settings文件里輸入
>```
MONGODB_URI = 'mongodb://localhost:27017'
MONGODB_DATABASE = 'scrapy'
DOWNLOAD_DELAY = 0.25 #用于防止被ban```
然后在pipeline文件直接用官網的代碼。只需要改動process_items函數的代碼和集合名。
>```
import pymongo
import pymongo
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from myproject.items import myitem
class myPipeline(object):
collection_name = 'scrapy_items'
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):
self.db[self.collection_name].insert(dict(item))
return item```
#第四章、圖片下載和文件下載 參考http://www.lxweimin.com/p/b5ae15cb131d
scrapy中圖片和文件下載暫時只支持存在系統目錄或者S3.
##圖片下載
在items文件中:
>```import scrapy
class MyItem(scrapy.Item):
image_urls = scrapy.Field() #用來存放圖片的SRC源地址
images = scrapy.Field() #儲存下載結果,當文件下載完后,images字段將被填充為一個2元素的元組。其中第一個為布爾值,表明是否成功下載,第二個是一個字典,含有相關信息。如
(True, {'checksum': '2b00042f7481c7b056c4b410d28f33cf',
'path': 'full/0a79c461a4062ac383dc4fade7bc09f1384a3910.jpg',
'url': 'http://www.example.com/files/product1.pdf'})
同理文件下載的item
在settings文件中配置:保存目錄,失效時間,縮略圖生成,過濾小圖片
IMAGES_STORE = "./圖片" #圖片儲存路徑,為當前項目目錄下的圖片文件夾
FILES_STORE = "./wenjian" #文件儲存路徑
FILES_EXPIRES = 90 #設置文件失效的時間
IMAGES_EXPIRES = 30 #設置圖片失效的時間```
IMAGES_THUMBS = {
'small': (50, 50),
'big': (270, 270),
} #設置縮略圖大小,當你使用這個特性時,圖片管道將使用下面的格式來創建各個特定尺寸的縮略圖:
<IMAGES_STORE>/thumbs/<size_name>/<image_id>.jpg
IMAGES_MIN_HEIGHT = 110 #過濾小圖片
IMAGES_MIN_WIDTH = 110 #過濾小圖片```
pipeline
經常需要在pipeline或者中間件中獲取settings的屬性,可以通過scrapy.crawler.Crawler.settings屬性或者
from scrapy.conf importsettings
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
if settings['LOG_ENABLED']:
print "log is enabled!" ```
每個圖片item保存在不同的目錄
class MyImagesPipeline(ImagesPipeline):
spider = None
def get_media_requests(self, item, info):
for url in item["image_urls"]:
yield scrapy.Request(url,meta={'sch_name': item["sch_name"]})
#file_path函數重寫,對圖片保存目錄進行設置
def file_path(self, request, response=None, info=None):
image_guid = request.url.split('/')[-1]
return "C:/pictures/full/%s/%s" % (request.meta['sch_name'],image_guid)
def item_completed(self, results, item, info):
image_paths = [x['path'] for ok, x in results if ok]
if not image_paths:
raise DropItem("Item contains no images")
return item