Scrapy爬取知乎用户信息以及人际拓扑关系
Scrapy爬取知乎用戶信息以及人際拓撲關系
1.生成項目
scrapy提供一個工具來生成項目,生成的項目中預置了一些文件,用戶需要在這些文件中添加自己的代碼。 打開命令行,執行:scrapy startproject tutorial,生成的項目類似下面的結構
tutorial/ scrapy.cfg tutorial/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py2.源碼分析
2.1文件成員介紹
####2.1.1 items.py
類需要繼承 scrapy.Item,爬取的主要目標就是從非結構性的數據源提取結構性數據,例如網頁。 Scrapy提供Item類來滿足這樣的需求。 該項目中定義了在爬取元素構造的知乎用戶屬性和知乎用戶關系兩大塊Item,為爬取后的數據轉化為結構性數據,同時,也為后面的持久化做準備. ####2.1.2 pipelines.py :當Item在Spider中被收集之后,它將會被傳遞到Item Pipeline,一些組件會按照一定的順序執行對Item的處理。
每個item pipeline組件(有時稱之為“Item Pipeline”)是實現了簡單方法的Python類。他們接收到Item并通過它執行一些行為,同時也決定此Item是否繼續通過pipeline,或是被丟棄而不再進行處理。
以下是item pipeline的一些典型應用:
- 清理HTML數據
- 驗證爬取的數據(檢查item包含某些字段)
- 查重(并丟棄)
- 將爬取結果保存到數據庫中 編寫你自己的item pipeline 編寫你自己的item pipeline很簡單,每個item pipeline組件是一個獨立的Python類,同時必須實現以下方法:
process_item(self, item, spider) 每個item pipeline組件都需要調用該方法,這個方法必須返回一個 Item (或任何繼承類)對象, 或是拋出 DropItem 異常,被丟棄的item將不會被之后的pipeline組件所處理。
該項目中就在該類中實現把數據持久化到mango數據庫中
參數: item (Item 對象) – 被爬取的item spider (Spider 對象) – 爬取該item的spider
import osfrom pymongo import MongoClient from zhihu.settings import MONGO_URI, PROJECT_DIR from zhihu.items import ZhihuPeopleItem, ZhihuRelationItem from zhihu.tools.async import download_picclass ZhihuPipeline(object):"""存儲數據"""def __init__(self, mongo_uri, mongo_db, image_dir):self.mongo_uri = mongo_uriself.mongo_db = mongo_dbself.image_dir = image_dirself.client = Noneself.db= Nonedef process_item(self, item, spider):"""處理item"""if isinstance(item, ZhihuPeopleItem):self._process_people(item)elif isinstance(item, ZhihuRelationItem):self._process_relation(item)return item####2.1.3 settings.py
配置文件,提供爬蟲系統參數的可配置化
####2.1.4 spiders 這個是一個包,可以定制自己的爬蟲代碼.如ZhihuSipder這個類就是知乎爬蟲的啟動類.
2.2 技術要點
####2.2.1 CrawlSpider
這里采用CrawlSpider,這個繼承了Spider的且,非常適合做全站數據爬取的類.
簡析上面的三個參數: 1.name:這個參數是每個自定義爬蟲必須要有的,唯一辨別你的自定義爬蟲,name當然也是使用命令啟動爬蟲的一個決定因素.啟動命令:scrapy crawl zhihu,其中的zhihu就是name屬性. 2.allowed_domains:鏈接中必須包含的域名. 3.start_url:爬蟲的入口地址,這里就是以我本人的知乎主頁為入口. ####2.2.2 FormRequest做登陸模塊
from scrapy.http import Request, FormRequestdef post_login(self, response):"""解析登陸頁面,發送登陸表單"""self.xsrf = Selector(response).xpath('//input[@name="_xsrf"]/@value').extract()[0]return [FormRequest('https://www.zhihu.com/login/email',method='POST',meta={'cookiejar': response.meta['cookiejar']},formdata={'_xsrf': self.xsrf,'email': 'xxxxxxxxx','password': 'xxxxxxxxx','remember_me': 'true'},callback=self.after_login)]####2.2.3 Requests and Responses Scrapy使用 Request 和 Response 對象爬取web站點。
一般來說,Request 對象在spiders中被生成并且最終傳遞到 下載器(Downloader),下載器對其進行處理并返回一個 Response 對象, Response 對象還會返回到生成request的spider中。
所有 Request and Response 的子類都會實現一些在基類中非必要的 功能。它們會在 Request subclasses 和 Response subclasses 兩部分進行詳細的說明。 下面是Request構造函數
class Request(object_ref):def __init__(self, url, callback=None, method='GET', headers=None, body=None,cookies=None, meta=None, encoding='utf-8', priority=0,dont_filter=False, errback=None):self._encoding = encoding # this one has to be set firstself.method = str(method).upper()self._set_url(url)self._set_body(body)assert isinstance(priority, int), "Request priority not an integer: %r" % priorityself.priority = priorityassert callback or not errback, "Cannot use errback without a callback"self.callback = callbackself.errback = errbackself.cookies = cookies or {}self.headers = Headers(headers or {}, encoding=encoding)self.dont_filter = dont_filterself._meta = dict(meta) if meta else None特別注意:參數:dont_filter
dont_filter(boolean) – indicates that this request should not be filtered by the scheduler. This is used when you want to perform an identical request multiple times, to ignore the duplicates filter. Use it with care, or you will get into crawling loops. Default to False.
解釋:scrapy url去重 Request對象參數的dont_filter=False,默認就是false 如程序所示,默認就是要進行url去重
show code:
ps: scrapy 中判斷重復內容的方法(RFPDupeFilter)
3 源碼地址
github地址 該目錄下的知乎爬蟲項目,即可下載源碼.
4 每日推薦
linux下命令窗口分配顯示一遍查看使用說明,一般敲代碼. 軟件名: tmux
效果圖:
轉載于:https://my.oschina.net/u/2523402/blog/752345
總結
以上是生活随笔為你收集整理的Scrapy爬取知乎用户信息以及人际拓扑关系的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: root卡顿解决方法,手机root后很卡
- 下一篇: VC++ OLE DB 读写数据库