Scrapy安装介绍及入门

来源:互联网 发布:淘宝大学毕业证 编辑:程序博客网 时间:2024/06/07 00:29

Scrapy安装介绍

一、 Scrapy简介

Scrapy is a fast high-level screen scraping and web crawling framework, used to crawl websites and extract structured data from their pages. It can be used for a wide range of purposes, from data mining to monitoring and automated testing.

官方主页: http://www.scrapy.org/

 

二、 安装Python2.7

官方主页:http://www.python.org/

下载地址:http://www.python.org/ftp/python/2.7.3/python-2.7.3.msi

 

1) 安装python

安装目录:D:\Python27

 

2) 添加环境变量

略System Properties -> Advanced -> Environment Variables - >System Variables -> Path -> Edit

 

3) 验证环境变量

T:\>set PathPath=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;D:\Rational\common;D:\Rational\ClearCase\bin;D:\Python27;D:\Python27\ScriptsPATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH

 

4) 验证Python

复制代码
T:\>pythonPython 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> exit()T:\>
复制代码

 

 

三、 安装Twisted

Twisted is an event-driven networking engine written in Python and licensed under the open source

 

1) 安装setuptools

Download, build, install, upgrade, and uninstall Python packages -- easily!

官方主页:http://pypi.python.org/pypi/setuptools

下载地址:http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11.win32-py2.7.exe

安装过程:略

 

2) 安装Zope.Interface

官方主页:http://pypi.python.org/pypi/zope.interface/

下载地址:http://pypi.python.org/packages/2.7/z/zope.interface/zope.interface-4.0.1-py2.7-win32.egg

安装过程:

复制代码
T:\>d:D:\>cd D:\Python27\ScriptsD:\Python27\Scripts>easy_install.exe zope.interface-4.0.1-py2.7-win32.eggProcessing zope.interface-4.0.1-py2.7-win32.eggcreating d:\python27\lib\site-packages\zope.interface-4.0.1-py2.7-win32.eggExtracting zope.interface-4.0.1-py2.7-win32.egg to d:\python27\lib\site-packagesAdding zope.interface 4.0.1 to easy-install.pth fileInstalled d:\python27\lib\site-packages\zope.interface-4.0.1-py2.7-win32.eggProcessing dependencies for zope.interface==4.0.1Finished processing dependencies for zope.interface==4.0.1D:\Python27\Scripts>
复制代码

 

验证安装:

D:\Python27\Scripts>pythonPython 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import zope.interface>>>

 

3) 安装Twisted

官方主页:http://twistedmatrix.com/trac/wiki/TwistedProject

下载地址:http://pypi.python.org/packages/2.7/T/Twisted/Twisted-12.1.0.win32-py2.7.msi

安装过程:略

 

 

四、 安装w3lib

官方主页:http://pypi.python.org/pypi/w3lib

下载地址: http://pypi.python.org/packages/source/w/w3lib/w3lib-1.2.tar.gz

解压过程:略

安装过程:

复制代码
T:\w3lib-1.2>python setup.py installrunning installrunning buildrunning build_pycreating buildcreating build\libcreating build\lib\w3libcopying w3lib\encoding.py -> build\lib\w3libcopying w3lib\form.py -> build\lib\w3libcopying w3lib\html.py -> build\lib\w3libcopying w3lib\http.py -> build\lib\w3libcopying w3lib\url.py -> build\lib\w3libcopying w3lib\util.py -> build\lib\w3libcopying w3lib\__init__.py -> build\lib\w3librunning install_libcreating D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\encoding.py -> D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\form.py -> D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\html.py -> D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\http.py -> D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\url.py -> D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\util.py -> D:\Python27\Lib\site-packages\w3libcopying build\lib\w3lib\__init__.py -> D:\Python27\Lib\site-packages\w3libbyte-compiling D:\Python27\Lib\site-packages\w3lib\encoding.py to encoding.pycbyte-compiling D:\Python27\Lib\site-packages\w3lib\form.py to form.pycbyte-compiling D:\Python27\Lib\site-packages\w3lib\html.py to html.pycbyte-compiling D:\Python27\Lib\site-packages\w3lib\http.py to http.pycbyte-compiling D:\Python27\Lib\site-packages\w3lib\url.py to url.pycbyte-compiling D:\Python27\Lib\site-packages\w3lib\util.py to util.pycbyte-compiling D:\Python27\Lib\site-packages\w3lib\__init__.py to __init__.pycrunning install_egg_infoWriting D:\Python27\Lib\site-packages\w3lib-1.2-py2.7.egg-infoT:\w3lib-1.2>
复制代码

 

验证安装:

T:\>pythonPython 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import w3lib>>> 

 

 

五、 安装libxml2

官方主页:http://users.skynet.be/sbi/libxml-python/http://pypi.python.org/pypi/pyOpenSSL

下载地址:http://users.skynet.be/sbi/libxml-python/binaries/libxml2-python-2.7.7.win32-py2.7.exe

安装过程:略

验证安装:

T:\>pythonPython 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import libxml2>>> 

 

 

六、 安装pyOpenSSL

官方主页:http://pypi.python.org/pypi/pyOpenSSL

下载地址:http://pypi.python.org/packages/2.7/p/pyOpenSSL/pyOpenSSL-0.13.winxp32-py2.7.msi

安装过程:略

验证安装:

T:\>pythonPython 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import OpenSSL>>>

 经测试,windows平台还需要安装pywin32-218.win32-py2.7

 

七、 安装Scrapy

官方主页:http://scrapy.org/

下载地址:http://pypi.python.org/packages/source/S/Scrapy/Scrapy-0.14.4.tar.gz

解压过程:略

安装过程:

复制代码
T:\Scrapy-0.14.4>python setup.py install……Installing easy_install-2.7-script.py script to D:\Python27\ScriptsInstalling easy_install-2.7.exe script to D:\Python27\ScriptsInstalling easy_install-2.7.exe.manifest script to D:\Python27\ScriptsUsing d:\python27\lib\site-packagesFinished processing dependencies for Scrapy==0.14.4T:\Scrapy-0.14.4>
复制代码

 

验证安装:

复制代码
T:\>scrapyScrapy 0.14.4 - no active projectUsage:  scrapy <command> [options] [args]Available commands:  fetch         Fetch a URL using the Scrapy downloader  runspider     Run a self-contained spider (without creating a project)  settings      Get settings values  shell         Interactive scraping console  startproject  Create new project  version       Print Scrapy version  view          Open URL in browser, as seen by ScrapyUse "scrapy <command> -h" to see more info about a commandT:\>
复制代码

 

Scrapy入门教程

关键字:scrapy 入门教程 爬虫 Spider
作者:http://www.cnblogs.com/txw1958/
出处:http://www.cnblogs.com/txw1958/archive/2012/07/16/scrapy-tutorial.html

 

在这篇入门教程中,我们假定你已经安装了Scrapy。如果你还没有安装,那么请参考安装指南。

我们将使用开放目录项目(dmoz)作为抓取的例子。

这篇入门教程将引导你完成如下任务:

  1. 创建一个新的Scrapy项目
  2. 定义提取的Item
  3. 写一个Spider用来爬行站点,并提取Items
  4. 写一个Item Pipeline用来存储提取出的Items

Scrapy是由Python编写的。如果你是Python新手,你也许希望从了解Python开始,以期最好的使用Scrapy。如果你对其它编程语言熟悉,想快速的学习Python,这里推荐 Dive Into Python。如果你对编程是新手,且想从Python开始学习编程,请看下面的对非程序员的Python资源列表。

 

新建工程

在抓取之前,你需要新建一个Scrapy工程。进入一个你想用来保存代码的目录,然后执行:

Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.T:\>scrapy startproject tutorialT:\>

这个命令会在当前目录下创建一个新目录tutorial,它的结构如下:

复制代码
T:\tutorial>tree /fFolder PATH listingVolume serial number is 0006EFCF C86A:7C52T:.│  scrapy.cfg│└─tutorial    │  items.py    │  pipelines.py    │  settings.py    │  __init__.py    │    └─spiders            __init__.py
复制代码

这些文件主要是:

  • scrapy.cfg: 项目配置文件
  • tutorial/: 项目python模块, 呆会代码将从这里导入
  • tutorial/items.py: 项目items文件
  • tutorial/pipelines.py: 项目管道文件
  • tutorial/settings.py: 项目配置文件
  • tutorial/spiders: 放置spider的目录

 

定义Item

Items是将要装载抓取的数据的容器,它工作方式像python里面的字典,但它提供更多的保护,比如对未定义的字段填充以防止拼写错误。

它通过创建一个scrapy.item.Item类来声明,定义它的属性为scrpy.item.Field对象,就像是一个对象关系映射(ORM). 
我们通过将需要的item模型化,来控制从dmoz.org获得的站点数据,比如我们要获得站点的名字,url和网站描述,我们定义这三种属性的域。要做到这点,我们编辑在tutorial目录下的items.py文件,我们的Item类将会是这样

from scrapy.item import Item, Field class DmozItem(Item):    title = Field()    link = Field()    desc = Field()

刚开始看起来可能会有些困惑,但是定义这些item能让你用其他Scrapy组件的时候知道你的 items到底是什么。

 

 

我们的第一个爬虫(Spider)

Spider是用户编写的类,用于从一个域(或域组)中抓取信息。

他们定义了用于下载的URL的初步列表,如何跟踪链接,以及如何来解析这些网页的内容用于提取items。

要建立一个Spider,你必须为scrapy.spider.BaseSpider创建一个子类,并确定三个主要的、强制的属性:

  • name:爬虫的识别名,它必须是唯一的,在不同的爬虫中你必须定义不同的名字.
  • start_urls:爬虫开始爬的一个URL列表。爬虫从这里开始抓取数据,所以,第一次下载的数据将会从这些URLS开始。其他子URL将会从这些起始URL中继承性生成。
  • parse():爬虫的方法,调用时候传入从每一个URL传回的Response对象作为参数,response将会是parse方法的唯一的一个参数,

这个方法负责解析返回的数据、匹配抓取的数据(解析为item)并跟踪更多的URL。

 

这是我们的第一只爬虫的代码,将其命名为dmoz_spider.py并保存在tutorial\spiders目录下。

复制代码
from scrapy.spider import BaseSpiderclass DmozSpider(BaseSpider):    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]        open(filename, 'wb').write(response.body)
复制代码

 

 

爬爬爬

为了让我们的爬虫工作,我们返回项目主目录执行以下命令

T:\tutorial>scrapy crawl dmoz

crawl dmoz 命令从dmoz.org域启动爬虫。 你将会获得如下类似输出 

复制代码
T:\tutorial>scrapy crawl dmoz2012-07-13 19:14:45+0800 [scrapy] INFO: Scrapy 0.14.4 started (bot: tutorial)2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware2012-07-13 19:14:45+0800 [scrapy] DEBUG: Enabled item pipelines:2012-07-13 19:14:45+0800 [dmoz] INFO: Spider opened2012-07-13 19:14:45+0800 [dmoz] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)2012-07-13 19:14:45+0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:60232012-07-13 19:14:45+0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:60802012-07-13 19:14:46+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/> (referer: None)2012-07-13 19:14:46+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> (referer: None)2012-07-13 19:14:46+0800 [dmoz] INFO: Closing spider (finished)2012-07-13 19:14:46+0800 [dmoz] INFO: Dumping spider stats:        {'downloader/request_bytes': 486,         'downloader/request_count': 2,         'downloader/request_method_count/GET': 2,         'downloader/response_bytes': 13063,         'downloader/response_count': 2,         'downloader/response_status_count/200': 2,         'finish_reason': 'finished',         'finish_time': datetime.datetime(2012, 7, 13, 11, 14, 46, 703000),         'scheduler/memory_enqueued': 2,         'start_time': datetime.datetime(2012, 7, 13, 11, 14, 45, 500000)}2012-07-13 19:14:46+0800 [dmoz] INFO: Spider closed (finished)2012-07-13 19:14:46+0800 [scrapy] INFO: Dumping global stats:        {}
复制代码

注意包含 [dmoz]的行 ,那对应着我们的爬虫。你可以看到start_urls中定义的每个URL都有日志行。因为这些URL是起始页面,所以他们没有引用(referrers),所以在每行的末尾你会看到 (referer: <None>). 
有趣的是,在我们的 parse  方法的作用下,两个文件被创建:分别是 Books 和 Resources,这两个文件中有URL的页面内容。 

发生了什么事情?

Scrapy为爬虫的 start_urls属性中的每个URL创建了一个 scrapy.http.Request 对象 ,并将爬虫的parse 方法指定为回调函数。 
这些 Request首先被调度,然后被执行,之后通过parse()方法,scrapy.http.Response 对象被返回,结果也被反馈给爬虫。

 

 

提取Item

选择器介绍

我们有很多方法从网站中提取数据。Scrapy 使用一种叫做 XPath selectors的机制,它基于 XPath表达式。如果你想了解更多selectors和其他机制你可以查阅资料http://doc.scrapy.org/topics/selectors.html#topics-selectors 
这是一些XPath表达式的例子和他们的含义

  • /html/head/title: 选择HTML文档<head>元素下面的<title> 标签。
  • /html/head/title/text(): 选择前面提到的<title> 元素下面的文本内容
  • //td: 选择所有 <td> 元素
  • //div[@class="mine"]: 选择所有包含 class="mine" 属性的div 标签元素

这只是几个使用XPath的简单例子,但是实际上XPath非常强大。如果你想了解更多XPATH的内容,我们向你推荐这个XPath教程http://www.w3schools.com/XPath/default.asp

为了方便使用XPaths,Scrapy提供XPathSelector 类, 有两种口味可以选择, HtmlXPathSelector (HTML数据解析) 和XmlXPathSelector (XML数据解析)。 为了使用他们你必须通过一个 Response 对象对他们进行实例化操作。你会发现Selector对象展示了文档的节点结构。因此,第一个实例化的selector必与根节点或者是整个目录有关 。 
Selectors 有三种方法

  • select():返回selectors列表, 每一个select表示一个xpath参数表达式选择的节点.
  • extract():返回一个unicode字符串,该字符串为XPath选择器返回的数据
  • re(): 返回unicode字符串列表,字符串作为参数由正则表达式提取出来

尝试在shell中使用Selectors

为了演示Selectors的用法,我们将用到 内建的Scrapy shell,这需要系统已经安装IPython (一个扩展python交互环境) 。

附IPython下载地址:http://pypi.python.org/pypi/ipython#downloads

要开始shell,首先进入项目顶层目录,然后输入

T:\tutorial>scrapy shell http://www.dmoz.org/Computers/Programming/Languages/Python/Books/

输出结果类似这样:

复制代码
2012-07-16 10:58:13+0800 [scrapy] INFO: Scrapy 0.14.4 started (bot: tutorial)2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled extensions: TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware2012-07-16 10:58:13+0800 [scrapy] DEBUG: Enabled item pipelines:2012-07-16 10:58:13+0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:60232012-07-16 10:58:13+0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:60802012-07-16 10:58:13+0800 [dmoz] INFO: Spider opened2012-07-16 10:58:18+0800 [dmoz] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> (referer: None)[s] Available Scrapy objects:[s]   hxs        <HtmlXPathSelector xpath=None data=u'<html><head><meta http-equiv="Content-Ty'>[s]   item       {}[s]   request    <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>[s]   response   <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>[s]   settings   <CrawlerSettings module=<module 'tutorial.settings' from 'T:\tutorial\tutorial\settings.pyc'>>[s]   spider     <DmozSpider 'dmoz' at 0x1f68230>[s] Useful shortcuts:[s]   shelp()           Shell help (print this help)[s]   fetch(req_or_url) Fetch request (or URL) and update local objects[s]   view(response)    View response in a browserWARNING: Readline services not available or not loaded.WARNING: Proper color support under MS Windows requires the pyreadline library.You can find it at:http://ipython.org/pyreadline.htmlGary's readline needs the ctypes module, from:http://starship.python.net/crew/theller/ctypes(Note that ctypes is already part of Python versions 2.5 and newer).Defaulting color scheme to 'NoColor'Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]Type "copyright", "credits" or "license" for more information.IPython 0.13 -- An enhanced Interactive Python.?         -> Introduction and overview of IPython's features.%quickref -> Quick reference.help      -> Python's own help system.object?   -> Details about 'object', use 'object??' for extra details.In [1]:
复制代码

Shell载入后,你将获得回应,这些内容被存储在本地变量 response 中,所以如果你输入response.body 你将会看到response的body部分,或者输入response.headers 来查看它的 header部分。 
Shell也实例化了两种selectors,一个是解析HTML的  hxs 变量,一个是解析 XML 的 xxs 变量。我们来看看里面有什么:

复制代码
In [1]: hxs.select('//title')Out[1]: [<HtmlXPathSelector xpath='//title' data=u'<title>Open Directory - Computers: Progr'>]In [2]: hxs.select('//title').extract()Out[2]: [u'<title>Open Directory - Computers: Programming: Languages: Python: Books</title>']In [3]: hxs.select('//title/text()')Out[3]: [<HtmlXPathSelector xpath='//title/text()' data=u'Open Directory - Computers: Programming:'>]In [4]: hxs.select('//title/text()').extract()Out[4]: [u'Open Directory - Computers: Programming: Languages: Python: Books']In [5]: hxs.select('//title/text()').re('(\w+):')Out[5]: [u'Computers', u'Programming', u'Languages', u'Python']In [6]:
复制代码

 

 


原创粉丝点击