scrapy的简单demo

    一个scrapy使用的demo,以后抓数据可以参考它

1.Items

# -*- 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 RssItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    link = scrapy.Field()
    description = scrapy.Field()
    lastBuildDate = scrapy.Field()
    generator = scrapy.Field()
    language = scrapy.Field()
    copyright = scrapy.Field()
    pubDate = scrapy.Field()
    items = scrapy.Field()

class NodeItem(scrapy.Item):
    title = scrapy.Field()
    link = scrapy.Field()
    description = scrapy.Field()
    author = scrapy.Field()
    comments = scrapy.Field()
    pubDate = scrapy.Field()
    guid = scrapy.Field()

class RowItem(scrapy.Item):
    name = scrapy.Field()
    sex = scrapy.Field()
    addr = scrapy.Field()
    email = scrapy.Field()


class GoodsItem(scrapy.Item):
    name = scrapy.Field()
    price = scrapy.Field()
    link = scrapy.Field()
    commnum = scrapy.Field()
    
class NewsLinkItem(scrapy.Item):
    name = scrapy.Field()
    link = scrapy.Field()

2.settings

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

# Scrapy settings for demo project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'demo'

SPIDER_MODULES = ['demo.spiders']
NEWSPIDER_MODULE = 'demo.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'demo (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 0.5
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'demo.middlewares.DemoSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'demo.middlewares.MyCustomDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'demo.pipelines.DemoPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

3.pipline

# -*- coding: utf-8 -*-
import json
import codecs
from demo.dbconnect import DbUtil
# 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


class DemoPipeline(object):
    
    
    def __init__(self):
        self.file = codecs.open("mydata.json", 'wb', encoding='utf-8')
        self.dbutil = DbUtil('127.0.0.1','longlh','solong1980','orders')
    def process_item(self, item, spider):
        #print(item)
        #print(spider.name)
        if spider.name is 'DangDangSpider':
            for i in range(0,len(item['name'])):
                name = item['name'][i]
                link = item['link'][i]
                price = item['price'][i]
                commnum = item['commnum'][i]
                goods ={'name':name,'link':link,'price':price,'commnum':commnum}
                line = json.dumps(dict(goods), ensure_ascii=False)
                line = str(line) + '\n'
                self.file.write(line)
        if spider.name is 'webcrawl':
            for i in range(0,len(item['name'])):
                name = item['name'][i]
                link = item['link'][i]
                print(name)
                print(link)
                print("insert into tbtable(name,link) values('" + name + "','" + link + "')")
                self.dbutil.add("insert into tbtable(name,link) values('" + name + "','" + link + "')")
        return item
    
    def close_spider(self, spider):
        self.file.close()
        self.dbutil.close()

4.db util

# -*- coding: utf-8 -*-
import pymysql
import logging
from pymysql import charset

class DbUtil():
    def __init__(self, host, user, passwd, db, port=3306):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db
        try:
            self.conn = pymysql.connect(host, user, passwd, db,charset='utf8')
        except Exception as e:
            logging.error(str(e))
            raise Exception("connect fail")
    def cursor(self):
        return self.conn.cursor()
    def select(self, sql):
        return self.cursor().execute(sql)
    def add(self, sql):
        self.conn.query(sql)
    def close(self):
        try:
            self.conn.commit()
        except Exception as e:
            print(str(e))
        finally:
            self.conn.close()

5.Spider

# -*- coding: utf-8 -*-
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from demo.items import NewsLinkItem


class WebcrawlSpider(CrawlSpider):
    name = 'webcrawl'
    allowed_domains = ['sohu.com']
    start_urls = ['http://sports.sohu.com/nba.shtml']

    rules = (
        Rule(LinkExtractor(allow=('.*?/n.*?shtml'),allow_domains=('sohu.com')), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        i = NewsLinkItem()
        i['name'] = response.xpath('/html/head/title/text()').extract()
        i['link'] = response.xpath('//link[@rel="canonical"]/@href').extract()
        return i

猜你喜欢

转载自solong1980.iteye.com/blog/2393513