利用scrapy制作网页爬虫

简单说明

name 定义爬虫名字,我们通过命令启动的时候用的就是这个名字,这个名字必须是唯一的
allowed_domains 包含了spider允许爬取的域名列表。当offsiteMiddleware启用时,域名不在列表中URL不会被访问,所以在爬虫文件中,每次生成Request请求时都会进行和这里的域名进行判断
start_urls 起始的url列表,这里会通过spider.Spider方法中会调用start_request循环请求这个列表中每个地址。
custom_settings 自定义配置,可以覆盖settings的配置,主要用于当我们对爬虫有特定需求设置的时候,设置的是以字典的方式设置:custom_settings = {}
from_crawler 这是一个类方法,我们定义这样一个类方法,可以通过crawler.settings.get()这种方式获取settings配置文件中的信息,同时这个也可以在pipeline中使用
start_requests() 这个方法必须返回一个可迭代对象,该对象包含了spider用于爬取的第一个Request请求,这个方法是在被继承的父类中spider.Spider中写的,默认是通过get请求,如果我们需要修改最开始的这个请求,可以重写这个方法,如我们想通过post请求
make_requests_from_url(url) 这个也是在父类中start_requests调用的,当然这个方法我们也可以重写
parse(response)这个其实默认的回调函数,负责处理response并返回处理的数据以及跟进的url,该方法以及其他的Request回调函数必须返回一个包含Request或Item的可迭代对象

1.利用scrapy框架构造爬虫文件

scrapy startproject fiction
cd fiction
scrapy genspider Fiction quanshuwang.com
tree

流程图

11701876-53699d234ddb9789.png
997599-20170718005824536-883249513.png

树形图

├── fiction
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── items.cpython-36.pyc
│   │   ├── pipelines.cpython-36.pyc
│   │   └── settings.cpython-36.pyc
│   ├── items.py
│   ├── middlewares.py
│   ├── pipelines.py
│   ├── settings.py
│   └── spiders
│       ├── Fiction.py
│       ├── __init__.py
│       └── __pycache__
│           ├── Fiction.cpython-36.pyc
│           └── __init__.cpython-36.pyc
└── scrapy.cfg

2.改造items文件

import scrapy
    class fictionItem(scrapy.Item):
            name = scrapy.Field()  # 小说名字
            chapter_name = scrapy.Field()  # 小说章节名字
            chapter_content = scrapy.Field()  # 小说章节内容

3.改造Fiction文件

# -*- coding: utf-8 -*-
import scrapy
import re
from fiction.items import fictionItem
from scrapy.http import Request
class fictionSpider(scrapy.Spider):
    name = 'Fiction'
    allowed_domains = ['quanshuwang.com']
    start_urls = [
        'http://www.quanshuwang.com/list/1_2.html',
        'http://www.quanshuwang.com/list/1_3.html',
        'http://www.quanshuwang.com/list/1_4.html',
        'http://www.quanshuwang.com/list/1_5.html',
        'http://www.quanshuwang.com/list/1_6.html',
        'http://www.quanshuwang.com/list/1_7.html',
        'http://www.quanshuwang.com/list/1_8.html',
        'http://www.quanshuwang.com/list/1_9.html',
        'http://www.quanshuwang.com/list/1_10.html',
    ]  # 全书网玄幻魔法类前10页

    # 获取每一本书的URL
    def parse(self, response):
        book_urls = response.xpath('//li/a[@class="l mr10"]/@href').extract()
        for book_url in book_urls:
            yield Request(book_url, callback=self.parse_read)

    # 获取马上阅读按钮的URL,进入章节目录
    def parse_read(self, response):
        read_url = response.xpath('//a[@class="reader"]/@href').extract()[0]
        yield Request(read_url, callback=self.parse_chapter)

    # 获取小说章节的URL
    def parse_chapter(self, response):
        chapter_urls = response.xpath('//div[@class="clearfix dirconone"]/li/a/@href').extract()
        for chapter_url in chapter_urls:
            yield Request(chapter_url, callback=self.parse_content)

    # 获取小说名字,章节的名字和内容
    def parse_content(self, response):
        # 小说名字
        name = response.xpath('//div[@class="main-index"]/a[@class="article_title"]/text()').extract_first()
        result = response.text
#对于scrapy.selector.unified.SelectorList对象,getall()==extract(),get()==extract_first()
#对于scrapy.selector.unified.Selector对象,getall()==extract(),get()!=extract_first()
        # 小说章节名字
        chapter_name = response.xpath('//strong[@class="l jieqi_title"]/text()').extract_first()
        # 小说章节内容
        chapter_content_reg = r'style5\(\);</script>(.*?)<script type="text/javascript">'
        chapter_content_2 = re.findall(chapter_content_reg, result, re.S)[0]
        chapter_content_1 = chapter_content_2.replace('    ', '')
        chapter_content = chapter_content_1.replace('<br />', '')

        item = fictionItem()
        item['name'] = name
        item['chapter_name'] = chapter_name
        item['chapter_content'] = chapter_content
        yield item

4.改造pipeline文件

# -*- coding: utf-8 -*-
import os
class fictionPipeline(object):
    def process_item(self, item, spider):
        curPath = '/Users/writ/Desktop'
        tempPath = str(item['name'])
        targetPath = curPath + os.path.sep + tempPath
        if not os.path.exists(targetPath):
            os.makedirs(targetPath)
        filename_path = '/Users/writ/Desktop' + os.path.sep + str(item['name']) + os.path.sep + str(item['chapter_name']) + '.txt'
        with open(filename_path, 'w', encoding='utf-8') as f:
            f.write(item['chapter_content'] + "\n")
        return item

5.改造setting文件

BOT_NAME = 'fiction'
SPIDER_MODULES = ['fiction.spiders']
NEWSPIDER_MODULE = 'fiction.spiders'
# Obey robots.txt rules
ROBOTSTXT_OBEY = 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',
}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'fiction.pipelines.fictionPipeline': 300,
}

6.执行文件

scrapy crawl Fiction
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值