创建scrapy项目

创建scrapy项目的命令:scrapy startproject +<项目名字>
scrapy startproject zongheng

创建爬虫

命令:在项目路径下执行:scrapy genspider +<爬虫名字> + <允许爬取的域名>

示例:

cd zongheng
scrapy genspider book zongheng

生成的目录和文件结果如下:

完善spider

在zongheng.py中修改内容如下:

import re

import scrapy


class BookSpider(scrapy.Spider):
    name = 'book'
    allowed_domains = ['zongheng']
    start_urls = ['http://book.zongheng/store.html']

    def parse(self, response):
        divs = response.xpath('//div[@class="bookinfo"]')
        for div in divs:
            item = {}
            item['书名'] = div.xpath('./div/a/text()').extract_first()
            item['作者'] = div.xpath('./div[2]/a/text()').extract_first()
            item['书籍分类'] = div.xpath('./div[2]/a[2]/text()').extract_first()
            item['简介'] = div.xpath('./div[3]/text()').extract_first()
            yield item

        # 列表下一页获取
        # 获取当前页的页号
        current_page = int(re.findall('page="(\d+)"', response.text)[0])
        # 获取总的页码数
        page_numbers = int(re.findall('count="(\d+)"', response.text)[0])
        # 计算下一页的页号
        next_page = current_page + 1
        # 如果下一页的页号小于总页码数, 就说明有下一页, 那么就根据这个页号生成下一页的URL
        if next_page < page_numbers:
            s = 'store/c0/c0/b0/u0/p{}/v9/s9/t0/u0/i1/ALL.html'.format(next_page)
            next_url = 'http://book.zongheng/' + s
            print(next_url)
            yield scrapy.Request(next_url, callback=self.parse)

在settings.py设置开启pipeline

ITEM_PIPELINES = {
    # 键(key)  完整类名: 模块.类名
    # 值(优先级): 是一个0-1000的整数, 越小越先执行
    'zongheng.pipelines.ZonghengPipeline': 400

#浏览器请求头
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'

初学爬虫,终极目标爬小说内容,最后,大家不要访问的太频繁了,服务器挂了不要找我

更多推荐

scrapy爬取纵横小说网所有小说信息