`

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

 

分享到:
评论

相关推荐

    点评.zip(写的一个scrapy的爬虫简单的demo)

    写的一个scrapy的爬虫简单的demo,这是通过使用scrapy爬虫爬取大众点评商家信息,这里只爬取了商家名字和星级

    Scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250

    经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo。这次我会以爬取豆瓣电影TOP250为例进一步为大家讲解一个完整爬虫的流程。 工具和环境 语言:python 2.7 IDE: Pycharm 浏览器:...

    网页抓取DEMO-可以运行的一个java项目

    网页抓取的简单demo,可以运行的一个项目,适合对网页抓取感兴趣的初学者,介绍了如何抓取到网页的页面

    python爬虫实现demo

    1. **简洁易读**: Python的语法非常简洁和易于理解,使得编写爬虫程序变得相对简单。与其他编程语言相比,Python代码通常更加可读,逻辑清晰,这样就可以更轻松地实现和维护爬虫程序。 2. **丰富的第三方库**: ...

    python实现的爬虫demo

    1. **简洁易读**: Python的语法非常简洁和易于理解,使得编写爬虫程序变得相对简单。与其他编程语言相比,Python代码通常更加可读,逻辑清晰,这样就可以更轻松地实现和维护爬虫程序。 2. **丰富的第三方库**: ...

    ScrapyUtils:抓取可变网页的简单工具

    创建一个方案> python trigger.py generate demoor> trigger.exe generate demo2.设定(demo / setting.py) 创建您的任务对象。 # generator your tasks in here.def generate_tasks ( ** kwargs ): for i in ...

    大数据中数据采集的几种方式.pdf

    这⾥我就⽤WebMagic做⼀个Demo试⼀试吧! 1.4跑⼀下WebMagic 百度后我找到了WebMagic的 照着⾥⾯的例⼦测试⼀下: ⾸先新建⼀个maven项⽬,是不是web项⽬都可以,只要是maven就⾏了。嗯,当然不要maven也可以⼿动导...

    一个敏捷强大的Java爬虫框架SeimiCrawler.zip

    设计思想上SeimiCrawler受Python的爬虫框架Scrapy启发很大,同时融合了Java语言本身特点与Spring的特性,并希望在国内更方便且普遍的使用更有效率的XPath解析HTML,所以SeimiCrawler默认的HTML解析器是JsoupXpath,...

Global site tag (gtag.js) - Google Analytics