scrapy爬取旋风网站APP

网址:http://www.xfdown.com/class/155_1.html

要求根据右侧的分类进行爬取,获取子页面的APP信息如名称、大小、出版商等一些信息,总数据27000多个,耗时20个小时,使用工具pycharm。废话少说直接上代码
遇到的问题:在爬取数据时,APP的公司和官方连接每个网页会有所不同,所以采取了两种xpath的情形进行采取。
注意事项:存储文件,写了两种的存储方式一种为csv,另一种为MongoDB,根据自己的情况进行选择,修改存储的方法,在settings.py文件中进行修改,不清楚的可以查看之前写的文章https://www.jianshu.com/p/5501827c55fc

app.py

import scrapy
import json
import re,random
from copy import deepcopy
import pprint,csv
from ..items import ScrapyAppItem


class GetHome(scrapy.Spider):
    def __init__(self):

        pass
    name = 'app'
    start_urls = ['http://www.xfdown.com/class/155_1.html']
    # allowed_domains = ['www.xfdown.com/']

    def parse(self, response):
        items_name = response.xpath('//*[@id="dlist"]/div[4]/div[3]/div[1]/ul/a')
        items_link=response.xpath('//*[@id="dlist"]/div[4]/div[3]/div[1]/ul/a')
        for bg_name,bg_link in zip(items_name,items_link):
            link = 'http://www.xfdown.com' + bg_link.xpath('./@href').get()
            name=bg_name.xpath('./text()').get()
            link_key=re.match(r'(http://www.xfdown.com/class/\d+)_\d+.html',link).group(1)
            yield scrapy.Request(link,callback=self.content,meta={'app_catalogue':name})
        pass

    def content(self, response):
        name = response.meta['app_catalogue']
        links=response.xpath('//*[@id="dlist"]/div[4]/div[2]/div[2]/ul/li/div[1]/div[2]/h3/a/@href')
        for link in links:
            app_link='http://www.xfdown.com'+link.get()
            yield scrapy.Request(url=app_link,callback=self.data,meta={'app_catalogue':name})
            pass
        next_url=response.xpath('//*[@id="dlist"]/div[4]/div[2]/div[2]/div/div/div[2]/a[@class="tsp_next"]/@href').get()
        if next_url is not None:
            print('http://www.xfdown.com'+next_url)
            yield scrapy.Request('http://www.xfdown.com'+next_url,callback=self.content,meta={'app_catalogue':name})
        else:
            print('此类页面结束!!!')

        pass

    def data(self,response):
        name = response.meta['app_catalogue']
        app_name =response.xpath('/html/body/div[4]/div[2]/div[1]/div/h1/text()').get()
        app_size =re.match(r'^(.*?): (.*?\w$)',response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[1]/text()').get()).group(2)
        app_style =re.match(r'^(.*?): (.*?\w$)',response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[2]/text()').get()).group(2)
        app_language = re.match(r'^(.*?): (.*?\w$)',response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[3]/text()').get()).group(2)
        app_updatetime = re.match(r'^(.*?): (.*?\w$)',response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[6]/text()').get()).group(2)
        try:
            app_company = re.search(r'(.*?):(.*?\w$)',
                                    response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[9]/text()').get()).group(2)
        except:
            app_company = response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[9]/a/text()').get()
        app_navigateto = response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[8]/text()').get()
        try:
            app_navigateto = re.search(r'(.*?):(.*?\w$)',
                                    response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[8]/text()').get()).group(2)
        except:
            app_navigateto = response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[8]/a/text()').get()

        app_platform = re.match(r'^(.*?): (.*?\w$)',response.xpath('/html/body/div[4]/div[2]/div[2]/ul/li[7]/text()').get()).group(2)
        app_abstract = response.xpath('/html/body/div[4]/div[3]/div[2]').get()
        items = ScrapyAppItem(app_name=app_name,app_size=app_size,app_style=app_style,app_platform=app_platform,
                              app_language=app_language,app_company=app_company,app_abstract=app_abstract,
                              app_navigateto=app_navigateto,app_catalogue=name,app_updatetime=app_updatetime)
        yield items
        pass
    pass

middlewares.py

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

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals


class ScrapyAppSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class ScrapyAppDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

import random
class UserAgent(object):
    USER_AGENTS = [
        'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Acoo Browser 1.98.744; .NET CLR 3.5.30729)',
        'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Acoo Browser 1.98.744; .NET CLR 3.5.30729)',
        'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Acoo Browser; GTB5; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)',
        'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; Acoo Browser; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Avant Browser)',
    ]
    def process_request(self, request, spider): #这里一定要使用process_request不然的话请求设置没用,为内置方法
        useragent = random.choice(self.USER_AGENTS)
        request.headers['User-Agent'] = useragent
        pass
    pass

settings.py

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

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

BOT_NAME = 'scrapy_app'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'scrapy_app (+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 https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 2
# 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 https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
   'scrapy_app.middlewares.ScrapyAppSpiderMiddleware': 543,
}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'scrapy_app.middlewares.UserAgent': 543,
}

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

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'scrapy_app.pipelines.ScrapyAppPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.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 https://docs.scrapy.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'

pipeline.py

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import csv
import pymongo
class ScrapyAppPipeline:
    def __init__(self):
        print('爬虫开始!!!')
        self.f = open('app.csv', 'a', newline='', encoding='gbk')
        self.write = csv.writer(self.f)
        self.write.writerow(['分类', '名称', '大小','类型', '语言', '最近更新时间',
                             '使用平台', '公司', '官网', '描述'])
        pass

    def start_spider(self):

        pass

    def process_item(self, item, spider):
        data_list = [item['app_catalogue'], item['app_name'], item['app_size'], item['app_style'],
                     item['app_language'], item['app_updatetime'], item['app_platform'], item['app_company'],
                     item['app_navigateto'], item['app_abstract']]
        self.write.writerow(data_list)

        pass

    def close_spider(self):
        self.f.close()
        pass


# from pymongo import MongoClient
# class MongoPipeline(object):
#     def __init__(self, databaseIp='127.0.0.1', databasePort=27017,
#                  mongodbName='dbtry'):
#         client = MongoClient(databaseIp, databasePort)
#         self.db = client[mongodbName]
#
#     def process_item(self, item, spider):
#         postItem = dict(item)  # 把item转化成字典形式
#         self.db.test.insert(postItem)  # 向数据库插入一条记录
#         return item  # 会在控制台输出原item数据,可以选择不写

如有问题可以留言,可相互交流讨论!!!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,254评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,875评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,682评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,896评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,015评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,152评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,208评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,962评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,388评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,700评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,867评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,551评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,186评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,901评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,142评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,689评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,757评论 2 351