python天然不用多說,擁有的爬蟲框架數不勝數。html
Java接觸的不是不少,因此知道的爬蟲框架很少。java
node接觸的更加很少,可是也淘到了不錯的幾個框架。node
C#做爲筆者除了Python之外比較熟悉的語言了。可是發現其爬蟲框架少的可憐。哎,不由嘆息。python
通常比價小型的爬蟲需求,我是直接使用requests庫 + bs4就解決了,再麻煩點就使用selenium解決js的異步 加載問題。相對比較大型的需求才使用框架,主要是便於管理以及擴展等。git
1.ScrapyScrapy是一個爲了爬取網站數據,提取結構性數據而編寫的應用框架。 能夠應用在包括數據挖掘,信息處理或存儲歷史數據等一系列的程序中。github
其最初是爲了 頁面抓取 (更確切來講, 網絡抓取 )所設計的, 也能夠應用在獲取API所返回的數據(例如 Amazon Associates Web Services ) 或者通用的網絡爬蟲。web
HTML, XML源數據 選擇及提取 的內置支持redis
提供了一系列在spider之間共享的可複用的過濾器(即 Item Loaders),對智能處理爬取數據提供了內置支持。sql
經過 feed導出 提供了多格式(JSON、CSV、XML),多存儲後端(FTP、S三、本地文件系統)的內置支持shell
提供了media pipeline,能夠 自動下載 爬取到的數據中的圖片(或者其餘資源)。
高擴展性。您能夠經過使用 signals ,設計好的API(中間件, extensions, pipelines)來定製實現您的功能。
內置的中間件及擴展爲下列功能提供了支持:
cookies and session 處理
HTTP 壓縮
HTTP 認證
HTTP 緩存
user-agent模擬
robots.txt
爬取深度限制
其餘
針對非英語語系中不標準或者錯誤的編碼聲明, 提供了自動檢測以及健壯的編碼支持。
支持根據模板生成爬蟲。在加速爬蟲建立的同時,保持在大型項目中的代碼更爲一致。詳細內容請參閱 genspider 命令。
針對多爬蟲下性能評估、失敗檢測,提供了可擴展的 狀態收集工具 。
提供 交互式shell終端 , 爲您測試XPath表達式,編寫和調試爬蟲提供了極大的方便
提供 System service, 簡化在生產環境的部署及運行
內置 Web service, 使您能夠監視及控制您的機器
內置 Telnet終端 ,經過在Scrapy進程中鉤入Python終端,使您能夠查看而且調試爬蟲
Logging 爲您在爬取過程當中捕捉錯誤提供了方便
支持 Sitemaps 爬取
具備緩存的DNS解析器
安裝
pip install scrapy
scrapy startproject tutorial ls tutorial/ scrapy.cfg tutorial/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py ...
import scrapyclass DmozSpider(scrapy.Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): filename = response.url.split("/")[-2] with open(filename, 'wb') as f: f.write(response.body)
scrapy crawl dmoz
這裏就簡單介紹一下,後面有時間詳細寫一些關於scrapy的文章,個人不少爬蟲的數據都是scrapy基礎上實現的。
2.PySpider項目地址:https://scrapy.org/
PySpider:一個國人編寫的強大的網絡爬蟲系統並帶有強大的WebUI。採用Python語言編寫,分佈式架構,支持多種數據庫後端,強大的WebUI支持腳本編輯器,任務監視器,項目管理器以及結果查看器。
image.png
python 腳本控制,能夠用任何你喜歡的html解析包(內置 pyquery)
WEB 界面編寫調試腳本,起停腳本,監控執行狀態,查看活動歷史,獲取結果產出
數據存儲支持MySQL, MongoDB, Redis, SQLite, Elasticsearch; PostgreSQL 及 SQLAlchemy
隊列服務支持RabbitMQ, Beanstalk, Redis 和 Kombu
支持抓取 JavaScript 的頁面
組件可替換,支持單機/分佈式部署,支持 Docker 部署
強大的調度控制,支持超時重爬及優先級設置
支持python2&3
代開web界面的編輯輸入代碼便可
from pyspider.libs.base_handler import *class Handler(BaseHandler): crawl_config = { } @every(minutes=24 * 60) def on_start(self): self.crawl('http://scrapy.org/', callback=self.index_page) @config(age=10 * 24 * 60 * 60) def index_page(self, response): for each in response.doc('a[href^="http"]').items(): self.crawl(each.attr.href, callback=self.detail_page) def detail_page(self, response): return { "url": response.url, "title": response.doc('title').text(), }
3.Crawley項目地址:https://github.com/binux/pyspider
Crawley能夠高速爬取對應網站的內容,支持關係和非關係數據庫,數據能夠導出爲JSON、XML等。
~$ crawley startproject [project_name] ~$ cd [project_name]
""" models.py """from crawley.persistance import Entity, UrlEntity, Field, Unicodeclass Package(Entity): #add your table fields here updated = Field(Unicode(255)) package = Field(Unicode(255)) description = Field(Unicode(255))
""" crawlers.py """from crawley.crawlers import BaseCrawlerfrom crawley.scrapers import BaseScraperfrom crawley.extractors import XPathExtractorfrom models import *class pypiScraper(BaseScraper): #specify the urls that can be scraped by this class matching_urls = ["%"] def scrape(self, response): #getting the current document's url. current_url = response.url #getting the html table. table = response.html.xpath("/html/body/div[5]/div/div/div[3]/table")[0] #for rows 1 to n-1 for tr in table[1:-1]: #obtaining the searched html inside the rows td_updated = tr[0] td_package = tr[1] package_link = td_package[0] td_description = tr[2] #storing data in Packages table Package(updated=td_updated.text, package=package_link.text, description=td_description.text)class pypiCrawler(BaseCrawler): #add your starting urls here start_urls = ["http://pypi.python.org/pypi"] #add your scraper classes here scrapers = [pypiScraper] #specify you maximum crawling depth level max_depth = 0 #select your favourite HTML parsing tool extractor = XPathExtractor
""" settings.py """import os PATH = os.path.dirname(os.path.abspath(__file__))#Don't change this if you don't have renamed the projectPROJECT_NAME = "pypi"PROJECT_ROOT = os.path.join(PATH, PROJECT_NAME) DATABASE_ENGINE = 'sqlite' DATABASE_NAME = 'pypi' DATABASE_USER = '' DATABASE_PASSWORD = '' DATABASE_HOST = '' DATABASE_PORT = '' SHOW_DEBUG_INFO = True
~$ crawley run
4.Portia項目地址:http://project.crawley-cloud.com/
Portia是一個開源可視化爬蟲工具,可以讓您在不須要任何編程知識的狀況下爬取網站!簡單地註釋您感興趣的頁面,Portia將建立一個蜘蛛來從相似的頁面提取數據。
這個使用時超級簡單,大家能夠看一下文檔。http://portia.readthedocs.io/en/latest/index.html
基於 scrapy 內核
可視化爬取內容,不須要任何開發專業知識
動態匹配相同模板的內容
5.Newspaper項目地址:https://github.com/scrapinghub/portia
Newspaper能夠用來提取新聞、文章和內容分析。使用多線程,支持10多種語言等。做者從requests庫的簡潔與強大獲得靈感,使用python開發的可用於提取文章內容的程序。
支持10多種語言而且全部的都是unicode編碼。
>>> from newspaper import Article>>> url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/'>>> article = Article(url)>>> article.download()>>> article.html'<!DOCTYPE HTML><html itemscope itemtype="http://...'>>> article.parse()>>> article.authors ['Leigh Ann Caldwell', 'John Honway']>>> article.publish_date datetime.datetime(2013, 12, 30, 0, 0)>>> article.text'Washington (CNN) -- Not everyone subscribes to a New Year's resolution...' >>> article.top_image 'http://someCDN.com/blah/blah/blah/file.png' >>> article.movies ['http://youtube.com/path/to/link.com', ...] >>> article.nlp() >>> article.keywords ['New Years', 'resolution', ...] >>> article.summary 'The study shows that 93% of people ...'
6.Beautiful Soup項目地址:https://github.com/codelucas/newspaper
Beautiful Soup 是一個能夠從HTML或XML文件中提取數據的Python庫.它可以經過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工做時間。這個我是使用的特別頻繁的。在獲取html元素,都是bs4完成的。
# -*- coding: utf-8 -*-import scrapyfrom bs4 import BeautifulSoupfrom urllib.parse import urljoinfrom six.moves import urllib DOMAIN = 'http://flagpedia.asia'class FlagSpider(scrapy.Spider): name = 'flag' allowed_domains = ['flagpedia.asia', 'flags.fmcdn.net'] start_urls = ['http://flagpedia.asia/index'] def parse(self, response): html_doc = response.body soup = BeautifulSoup(html_doc, 'html.parser') a = soup.findAll('td', class_="td-flag") for i in a: url = i.a.attrs.get("href") full_url = urljoin(DOMAIN, url) yield scrapy.Request(full_url, callback=self.parse_news) def parse_news(self, response): html_doc = response.body soup = BeautifulSoup(html_doc, 'html.parser') p = soup.find("p", id="flag-detail") img_url = p.img.attrs.get("srcset").split(" 2x")[0] url = "http:" + img_url img_name = img_url.split("/")[-1] urllib.request.urlretrieve(url, "/Users/youdi/Project/python/Rino_nakasone_backend/RinoNakasone/flag/{}".format(img_name)) print(url)
7.Grab項目地址:https://www.crummy.com/software/BeautifulSoup/bs4/doc/
Grab是一個用於構建Web刮板的Python框架。藉助Grab,您能夠構建各類複雜的網頁抓取工具,從簡單的5行腳本處處理數百萬個網頁的複雜異步網站抓取工具。Grab提供一個API用於執行網絡請求和處理接收到的內容,例如與HTML文檔的DOM樹進行交互。
8.Cola項目地址:http://docs.grablib.org/en/latest/#grab-spider-user-manual
Cola是一個分佈式的爬蟲框架,對於用戶來講,只需編寫幾個特定的函數,而無需關注分佈式運行的細節。任務會自動分配到多臺機器上,整個過程對用戶是透明的。
9.selenium項目地址:https://github.com/chineking/cola
Selenium 是自動化測試工具。它支持各類瀏覽器,包括 Chrome,Safari,Firefox 等主流界面式瀏覽器,若是在這些瀏覽器裏面安裝一個 Selenium 的插件,能夠方便地實現Web界面的測試. Selenium 支持瀏覽器驅動。Selenium支持多種語言開發,好比 Java,C,Ruby等等,PhantomJS 用來渲染解析JS,Selenium 用來驅動以及與 Python 的對接,Python 進行後期的處理。
from selenium import webdriverfrom selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('http://www.yahoo.com')assert 'Yahoo' in browser.title elem = browser.find_element_by_name('p') # Find the search boxelem.send_keys('seleniumhq' + Keys.RETURN) browser.quit()
10 .Python-goose框架項目地址:http://seleniumhq.github.io/selenium/docs/api/py/
Python-goose框架可提取的信息包括:
文章主體內容
文章主要圖片
文章中嵌入的任何Youtube/Vimeo視頻
元描述
元標籤
>>> from goose import Goose >>> url = 'http://edition.cnn.com/2012/02/22/world/europe/uk-occupy-london/index.html?hpt=ieu_c2'>>> g = Goose() >>> article = g.extract(url=url) >>> article.title u'Occupy London loses eviction fight'>>> article.meta_description"Occupy London protesters who have been camped outside the landmark St. Paul's Cathedral for the past four months lost their court bid to avoid eviction Wednesday in a decision made by London's Court of Appeal.">>> article.cleaned_text[:150] (CNN) -- Occupy London protesters who have been camped outside the landmark St. Paul's Cathedral for the past four months lost their court bid to avoi >>> article.top_image.src http://i2.cdn.turner.com/cnn/dam/assets/111017024308-occupy-london-st-paul-s-cathedral-story-top.jpg
項目地址:https://github.com/grangier/python-goose
做者:絕地無雙