python爬虫框架实例项目_常用python爬虫框架整理

Python中好用的爬虫框架

一般比价小型的爬虫需求,我是直接使用requests库 + bs4就解决了,再麻烦点就使用selenium解决js的异步 加载问题。相对比较大型的需求才使用框架,主要是便于管理以及扩展等。

1.Scrapy

Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架。 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。

其最初是为了 页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫。

AAffA0nNPuCLAAAAAElFTkSuQmCC

特性:HTML, XML源数据 选择及提取 的内置支持

提供了一系列在spider之间共享的可复用的过滤器(即 Item Loaders),对智能处理爬取数据提供了内置支持。

通过 feed导出 提供了多格式(JSON、CSV、XML),多存储后端(FTP、S3、本地文件系统)的内置支持

提供了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

PySpider:一个国人编写的强大的网络爬虫系统并带有强大的WebUI。采用Python语言编写,分布式架构,支持多种数据库后端,强大的WebUI支持脚本编辑器,任务监视器,项目管理器以及结果查看器。

AAffA0nNPuCLAAAAAElFTkSuQmCC

image.pngpython 脚本控制,可以用任何你喜欢的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

Crawley可以高速爬取对应网站的内容,支持关系和非关系数据库,数据可以导出为JSON、XML等。

AAffA0nNPuCLAAAAAElFTkSuQmCC

创建project~$ crawley startproject [project_name]

~$ cd [project_name]

定义models""" 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

Portia是一个开源可视化爬虫工具,可让您在不需要任何编程知识的情况下爬取网站!简单地注释您感兴趣的页面,Portia将创建一个蜘蛛来从类似的页面提取数据。

这个使用时超级简单,你们可以看一下文档。http://portia.readthedocs.io/en/latest/index.html基于 scrapy 内核

可视化爬取内容,不需要任何开发专业知识

动态匹配相同模板的内容

5.Newspaper

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'AAffA0nNPuCLAAAAAElFTkSuQmCC

示例# -*- 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

Grab是一个用于构建Web刮板的Python框架。借助Grab,您可以构建各种复杂的网页抓取工具,从简单的5行脚本到处理数百万个网页的复杂异步网站抓取工具。Grab提供一个API用于执行网络请求和处理接收到的内容,例如与HTML文档的DOM树进行交互。

8.Cola

Cola是一个分布式的爬虫框架,对于用户来说,只需编写几个特定的函数,而无需关注分布式运行的细节。任务会自动分配到多台机器上,整个过程对用户是透明的。

9.selenium

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框架

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://www.jianshu.com/p/59ead750099a

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值