scrapy筆記

scrapy源碼https://github.com/scrapy/scrapy/tree/master/scrapy

第一章、scrapy的模塊

有spiders,selector,http,linkextractors,item,loader,exceptions,pipeline等包。
其中,在scrapy的目錄下含有一些快捷的函數(shù),如

scrapy.Spider()(繼承于spiders包),
scrapy.Selector()(繼承于selector包),,
scrapy.Item() (繼承于item包),
scrapy.Request/FormRequest(繼承于http包)。

spiders模塊

常用Rule,CrawlSpider等函數(shù)。

一般爬蟲scrapy.spiders.Spider,其他爬蟲都是繼承此爬蟲。
鏈接爬蟲scrapy.spiders.CrawlSpider,
網(wǎng)站爬蟲scrapy.spiders.SitemapSpider
XML源爬蟲scrapy.spiders.XMLFeedSpider
CSV源爬蟲scrapy.spiders.CSVFeedSpider

linkextractors模塊

常用LinkExtractor()函數(shù)。

http模塊

常用HtmlResponse()函數(shù)
scrapy.http.Request()
scrapy.http.FormRequest()

item模塊

常用Item(),Field()函數(shù)

loader模塊

常用ItemLoader函數(shù)

exceptions模塊

常用DropItem函數(shù)

pipeline

常用image,file包函數(shù)

第二章、選擇器 scrapy.selector.Selector(response=None, text=None, type=None)

在scrapy中使用選擇器對(duì)response進(jìn)行解析。如response.xpath()。此時(shí)response已經(jīng)自動(dòng)被scrapy轉(zhuǎn)化成了選擇器。選擇器可以由文本或者TextResponse構(gòu)造形成,如:

from scrapy.http import HtmlResponse```
文本構(gòu)造

 Selector(text=body).xpath('//span/text()').extract()```
TextResponse構(gòu)造
 ```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()方法,前兩個(gè)返回字符串列表,后兩個(gè)返回字符串列表的第一個(gè)字符串。

##xpath
xpath("http://div")會(huì)得到文檔所有的div節(jié)點(diǎn)構(gòu)成的選擇器
> ```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獲取多個(gè)標(biāo)簽下的文本
> ```sel.xpath("http://div").xpath("string(.)").extract()#返回一個(gè)列表,每個(gè)元素都是一個(gè)div節(jié)點(diǎn)下所有的文本。```

獲取指定文本值的元素
 >```sel.xpath("http://a[contains(., 'Next Page')]").extract()
sel.xpath("http://a[text()='Next Page']").extract()```

選擇器,在選擇標(biāo)簽易變的文本時(shí)記得用
>```xpath("string(.)")```

在數(shù)據(jù)項(xiàng)易減少的文本時(shí),用
>```xpath("http://div[contains(text(),'word')]")```

可以利用兄弟父子節(jié)點(diǎn)選取。

#第三章、itempipeline
itempipeline是對(duì)spider產(chǎn)生的item進(jìn)行處理。有清洗,驗(yàn)證,檢查,儲(chǔ)存等功能。itempipeline含有四個(gè)方法:
>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```

##儲(chǔ)存到mongoDB
在settings文件里輸入
>```
MONGODB_URI = 'mongodb://localhost:27017'
MONGODB_DATABASE = 'scrapy'
DOWNLOAD_DELAY = 0.25 #用于防止被ban```

然后在pipeline文件直接用官網(wǎng)的代碼。只需要改動(dòng)process_items函數(shù)的代碼和集合名。
>```
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.itdecent.cn/p/b5ae15cb131d
scrapy中圖片和文件下載暫時(shí)只支持存在系統(tǒng)目錄或者S3.
##圖片下載
在items文件中:
>```import scrapy
 class MyItem(scrapy.Item):
    image_urls = scrapy.Field() #用來存放圖片的SRC源地址
    images = scrapy.Field() #儲(chǔ)存下載結(jié)果,當(dāng)文件下載完后,images字段將被填充為一個(gè)2元素的元組。其中第一個(gè)為布爾值,表明是否成功下載,第二個(gè)是一個(gè)字典,含有相關(guān)信息。如
(True,  {'checksum': '2b00042f7481c7b056c4b410d28f33cf',
   'path': 'full/0a79c461a4062ac383dc4fade7bc09f1384a3910.jpg',
   'url': 'http://www.example.com/files/product1.pdf'})

同理文件下載的item
在settings文件中配置:保存目錄,失效時(shí)間,縮略圖生成,過濾小圖片

IMAGES_STORE = "./圖片" #圖片儲(chǔ)存路徑,為當(dāng)前項(xiàng)目目錄下的圖片文件夾
FILES_STORE = "./wenjian" #文件儲(chǔ)存路徑
FILES_EXPIRES = 90 #設(shè)置文件失效的時(shí)間
IMAGES_EXPIRES = 30 #設(shè)置圖片失效的時(shí)間```

IMAGES_THUMBS = {
'small': (50, 50),
'big': (270, 270),
} #設(shè)置縮略圖大小,當(dāng)你使用這個(gè)特性時(shí),圖片管道將使用下面的格式來創(chuàng)建各個(gè)特定尺寸的縮略圖:
<IMAGES_STORE>/thumbs/<size_name>/<image_id>.jpg

IMAGES_MIN_HEIGHT = 110 #過濾小圖片
IMAGES_MIN_WIDTH = 110 #過濾小圖片```

pipeline

經(jīng)常需要在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!"  ```

每個(gè)圖片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函數(shù)重寫,對(duì)圖片保存目錄進(jìn)行設(shè)置 
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容