Python Scrapy 框架学习01

参考官方文档:http://scrapy-chs.readthedocs.io/zh_CN/1.0/intro/tutorial.html#spider 学习笔记

安装

安装分别在ubunutMAC系统下安装,过程如下:

ubuntu系统:

# 使用pip安装Scrapy
sudo pip install Scrapy
# 遇到报错,报哪个包没有,就是用pip安装哪个

MAC系统:

# 先确保已经安装 xcode
xcode-select --install
# 使用 pip 安装 Scrapy
sudo pip install Scrapy

# 遇到报错 关于six-1.4.1的,无法升级到新的版本。如下两种解决办法:
1、 sudo pip install scrapy --ignore-installed six # 跳过
2、 sudo easy_install "six>=1.5.2" # 使用easy_install 升级six。然后安装

创建项目:

$ scrapy startproject tutorial  # 创建项目
$ cd tutorial/ ; tree           # 进入到目录,并展示目录结构
.
├── scrapy.cfg
└── tutorial
    ├── __init__.py
    ├── items.py                # 保存爬去到的数据的容器,继承 scrapy.Item 类
    ├── pipelines.py
    ├── settings.py
    └── spiders
        └── __init__.py
        └── dmoz_spider.py       # 该文件为自己创建,继承 scrapy.Spider 类。定义属性:
                                 # name(唯一,区别spider)
                                 # start_urls(spider启动时进行爬去的列表,第一个被获取到
                                 的页面将是其中之一。 后续的URL则从初始的URL获取到的数据中提
                                 取)
                                 # pasrse() 方法,被调用时,每个初始URL完成下载后生成的
                                 Response 对象将会作为唯一的参数传递给该函数。 该方法负责解
                                 析返回的数据(response data),提取数据(生成item)以及生成
                                 需要进一步处理的URL的 Request 对象。

编写第一个爬虫

目的:获取url页面源码。(并未用到上边定义的Items)

创建一个spider,继承scrapy.Spider类,并定义一些属性:

  • name: 用于区别Spider。 该名字必须是唯一的,不可以为不同的Spider设定相同的名字。
  • start_urls: 包含了Spider在启动时进行爬取的url列表。 因此,第一个被获取到的页面将是其中之一。 后续的URL则从初始的URL获取到的数据中提取
  • parse():spider的一个方法。 被调用时,每个初始URL完成下载后生成的Response(页面内容)对象将会作为唯一的参数传递给该函数。 该方法负责解析返回的数据(response data),提取数据(生成item)以及生成需要进一步处理的URLRequest对象。

tutorial/spiders目录中创建dmoz_spider.py,如下:

#coding=utf-8
import scrapy

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allow_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
    ]

#----- 从start_urls中读取页面源码信息,并写入本地---#
    def parse(self,response):
        # reponse.body 会输出请求url的源码,response.url 是所请求的 url 地址
        # 通过下面的输出语句发现,start_urls 中的url地址的请求结果被分别带入到该方法中。
        print "debug---------"
        print response.body
        print response.url
        print "debug----------"

        # 过滤出请求 url 地址的最后一段,并以该段的名字来创建文件,并写入对应的网页源码。
        filename = response.url.split("/")[-2] + '.html'
        with open(filename,"wb") as f:
            f.write(response.body)

执行:

进入项目的根目录,执行下列命令启动spider

$ scrapy crawl dmoz

执行结果:在项目目录下,会生成两个文件,Books.htmlResources.html,文件内容分别是两个url页面的源码。

编写第二个项目(从选定的url地址中提取我们想要的信息)

定义Item

Item是保存爬取到的数据的容器。其使用方法和字典类似,虽然可以在Scrapy中直接使用dict,但是Item提供了额外保护机制来避免拼写错误导致的未定义字段错误。

编辑tutorial目录中的items.py文件,根据我们需要获取到的数据对item进行建模。下边分别定义了titleurl和网站的描述。

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class TutorialItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()  
    link = scrapy.Field()
    desc = scrapy.Field()

通过开发者工具对页面的源码进行分析,我们要提取的信息如下:


源码分析

tutorial/spiders目录中创建dmoz_spider.py,如下:

#coding=utf-8
import scrapy
from tutorial.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allow_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
    ]

# ----- 从start_urls中的页面源码中提取自己需要的,title、link、简介
    def parse(self, response):

        for sel in response.xpath('//*[@class="title-and-desc"]'):
        # item 对象是自定义的 python 字典,可以使用标准的字典语法来获取到每个段子的值,字段就是之前在items.py文件中用Field赋值的属性。
            item = DmozItem()
            item['title'] = sel.xpath('a/div/text()').extract()
            item['link'] = sel.xpath('a/@href').extract()
            item['desc'] = sel.xpath('div/text()').extract()
            yield item

执行:

进入项目的根目录,执行下列命令启动spider

$ scrapy crawl dmoz

在输出的debug信息中,可以看到生成的items列表。更直观一点可以将items写入文件:

$  scrapy crawl dmoz -o items.json -t josn
# -o 指定文件名称  -t 指定格式

查看items.json内容:

$ cat items.json | head -n 5
[
{"title": ["eff-bot's Daily Python URL "], "link": ["http://www.pythonware.com/daily/"], "desc": ["\r\n\t\t\t\r\n                                    Contains links to assorted resources from the Python universe, compiled by PythonWare.\r\n                                    ", "\r\n                                  "]},
{"title": ["O'Reilly Python Center "], "link": ["http://oreilly.com/python/"], "desc": ["\r\n\t\t\t\r\n                                    Features Python books, resources, news and articles.\r\n                                    ", "\r\n                                  "]},
{"title": ["Python Developer's Guide "], "link": ["https://www.python.org/dev/"], "desc": ["\r\n\t\t\t\r\n                                    Resources for reporting bugs, accessing the Python source tree with CVS and taking part in the development of Python.\r\n                                    ", "\r\n                                  "]},
{"title": ["Social Bug "], "link": ["http://win32com.goermezer.de/"], "desc": ["\r\n\t\t\t\r\n                                    Scripts, examples and news about Python programming for the Windows platform.\r\n                                    ", "\r\n                                  "]}

追踪链接项目

上边两个项目,url地址都是直接给出,现在需要将一个页面中的url地址提取出来,并依次进行处理。

http://www.dmoz.org/Computers/Programming/Languages/Python/Related categories部分的url地址。如图:

网站源码

更改tutorial/items.py文件,加入fromurl,来表明这个信息来自哪个链接。如下:

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class DmozItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    link = scrapy.Field()
    desc = scrapy.Field()
    fromurl = scrapy.Field()

tutorial/spiders目录中创建dmoz_spider.py,如下:

#coding=utf-8
import scrapy
from tutorial.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allow_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python/"
    ]

# ----- 追踪链接----#

    def parse(self, response):
# 提取需要爬取的链接,产生(yield)一个请求, 该请求使用 parse_dir_contents() 方法作为回调函数, 用于最终产生我们想要的数据.。
        print response.url
        for link in response.xpath('//div[@class="see-also-row"]/a/@href'):
            url = response.urljoin(link.extract())
            yield scrapy.Request(url,callback=self.parse_dir_contents)

    def parse_dir_contents(self,response):
# 提取信息,放入item中。这边增加了一个fromurl,所以在items.py 文件中,也要加入。
        for sel in response.xpath('//*[@class="title-and-desc"]'):
            item = DmozItem()
            item['title'] = sel.xpath('a/div/text()').extract()
            item['link'] = sel.xpath('a/@href').extract()
            item['fromurl'] = response.url
            item['desc'] = sel.xpath('div/text()').extract()
            yield  item

执行:

进入项目的根目录,执行下列命令启动spider

$  scrapy crawl dmoz -o items1.json -t josn

查看items1.json内容:

cat items2.json | head -n 5
[
{"link": ["http://en.wikipedia.org/wiki/Bytecode"], "title": ["Bytecode "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Interpreted/Bytecode/", "desc": ["\r\n\t\t\t\r\n                                    Growing article, with links to many related topics. [Wikipedia, open content, GNU FDL]\r\n                                    ", "\r\n                                  "]},
{"link": ["http://www.parrotcode.org/"], "title": ["Parrotcode "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Interpreted/Bytecode/", "desc": ["\r\n\t\t\t\r\n                                    Home of Parrot Virtual Machine, made for dynamic languages, originally a target for Perl 6 compiler, hosts many language implementations in varied stages of completion: Tcl, Javascript, Ruby, Lua, Scheme, PHP, Python, Perl 6, APL, .NET. Open source.\r\n                                    ", "\r\n                                  "]},
{"link": ["http://vvm.lip6.fr/"], "title": ["Virtual Virtual Machine "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Interpreted/Bytecode/", "desc": ["\r\n\t\t\t\r\n                                    VVM overview, history, members, projects, realizations, publications.\r\n                                    ", "\r\n                                  "]},
{"link": ["http://os.inf.tu-dresden.de/L4/l3elan.html"], "title": ["ELAN "], "fromurl": "http://www.dmoz.org/Computers/Programming/Languages/Multiparadigm/", "desc": ["\r\n\t\t\t\r\n                                    Created 1974 by Technical University of Berlin group, as alternative to BASIC in teaching, for systematic programming, and related styles: top-down, bottom-up, recursive, modular, syntax-directed. Descriptions, brief resource list, documents. English, Deutsch.\r\n                                    ", "\r\n                                  "]},
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339

推荐阅读更多精彩内容