参照 http://blog.youkuaiyun.com/u012150179/article/details/32911511,谢谢
个人总结
1、创建项目
scapy startproject w3school
2、在items.py中定义Item容器。也就是编写items.py内容
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy.item import Item,Field
class W3schoolItem(Item):
title = Field()
link = Field()
desc = Field()
上面定义了自己的W3schoolItem类,它继承自scrapy的Item(这里没有显示定义W3schoolItem的__init__()方法,也正因为如此,python也会为你自动调用基类的__init__(),否则必须显式在子类的__init__()中调用基类__init__()),之后声明W3schoolItem中元素并使用Field定义。到此items.py就OK了
3、在pipelines.py中编写W3schoolPipeline实现对item的处理
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import codecs
class W3SchoolPipeline(object):
def __init__(self):
self.file = codecs.open('w3school_data_utf8.json', 'wb', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item)) + '\n'
# print line
self.file.write(line.decode("unicode_escape"))
return item
其中的process_item方法是必须调用的用来处理item,并且返回值必须为Item类的对象,或者是抛出DropItem异常。并且上述方法将得到的item实现解码,以便正常显示中文,最终保存到json文件中。
注意:在编写完pipeline后,为了能够启动它,必须将其加入到ITEM_PIPLINES配置中,即在 settings.py中加入下面一句:# -*- coding: utf-8 -*-
# Scrapy settings for w3school project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'w3school'
SPIDER_MODULES = ['w3school.spiders']
NEWSPIDER_MODULE = 'w3school.spiders'
ITEM_PIPELINES = {
'w3school.pipelines.W3SchoolPipeline':300
}
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'w3school (+http://www.yourdomain.com)'
5、
编写爬虫
spider/文件夹下编写w3cshool_spider.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy import log
from w3school.items import W3schoolItem
class W3schoolSpider(Spider):
"""爬取w3school标签"""
#log.start("log",loglevel='INFO')
name = "w3school"
allowed_domains = ["w3school.com.cn"]
start_urls = [
"http://www.w3school.com.cn/xml/xml_syntax.asp"
]
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//div[@id="navsecond"]/div[@id="course"]/ul[1]/li')
items = []
for site in sites:
item = W3schoolItem()
title = site.xpath('a/text()').extract()
link = site.xpath('a/@href').extract()
desc = site.xpath('a/@title').extract()
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
#记录
log.msg("Appending item...",level='INFO')
log.msg("Append done.",level='INFO')
return items
注意点:
1、 需要注意的是编写的spider必须继承自scrapy的Spider类
属性name即spider唯一名字,start_url可以理解为爬取入口。
2、parse方法。
parse()是对scrapy.Spider类的override。
3、网页中的数据提取机制
scrapy使用选择器Selector并通过XPath实现数据的提取。关于XPath 推荐w3school的教程
6、执行。
scrapy crawl w3school --set LOG_FILE=log
在目录下生成log和w3school_data_utf8.json文件
小工具:
关于网页代码中意向信息的查找可以借助几个工具:
第一个——Firefox插件Firebug。
第二个——Firefox插件XPath。可以快速的在网页中对xpath表达式的正确性进行验证。
第三个——scrapy shell.关于其使用可以查看教程。