zoukankan      html  css  js  c++  java
  • 使用scrapy爬虫,爬取17k小说网的案例-方法二

    楼主准备爬取此页面的小说,此页面一共有125章

    我们点击进去第一章和第一百二十五章发现了一个规律

    我们看到此链接的  http://www.17k.com/chapter/271047/6336386.html ->http://www.17k.com/chapter/271047/6336510.html 

    6336386依次递增到6336510 我们根据此灵感 得到下面的spiders核心的代码

    # -*- coding: utf-8 -*-
    import scrapy
    from k17.items import K17Item
    import json
    class A17kSpider(scrapy.Spider):
        name = '17k'   
    
        allowed_domains = ['17k.com']
        start_urls = ['http://www.17k.com/chapter/271047/6336386.html']
        def parse(self, response):
            for i in range(6336386, 6336510 + 1):
                new_url="http://www.17k.com/chapter/271047/"+str(i)+".html"
                yield scrapy.Request(new_url, callback=self.next_parse) 
        def next_parse(self,response):
            for bb in response.xpath('//div[@class="readArea"]/div[@class="readAreaBox content"]'):
                    item=K17Item()
                    title=bb.xpath("h1/text()").extract()
    new_title=(''.join(title).replace(' ','')).strip() item['title']=new_title dec= bb.xpath("div[@class='p']/text()").extract()
    dec_new=((''.join(dec).replace(' ','')).replace('u3000','')).strip() ###去除内容中的 和u3000和空格的问题 item['describe'] = dec_new yield item

    我们在pipelines.py最后得到最终结果

    import json
    class K17Pipeline(object):
        def process_item(self, item, spider):
            return item
        #初始化时指定要操作的文件
        def __init__(self):
            self.file = open('item.json', 'w', encoding='utf-8')
        # 存储数据,将 Item 实例作为 json 数据写入到文件中
        def process_item(self, item, spider):
            lines = json.dumps(dict(item), ensure_ascii=False) + '
    '
            self.file.write(lines)
            return item
        # 处理结束后关闭 文件 IO 流
        def close_spider(self, spider):
            self.file.close()

  • 相关阅读:
    Linux下应急工具
    Windows NTLM Hash和Hash传递、Key传递攻击
    渗透中Meterpreter基本操作和对应的windows上的排查或者现象
    捕获一款无名挖矿木马(门罗币)样本分析
    Python守护进程和脚本单例运行
    iOS 支付宝支付
    iOS UI进阶-6.0 手势
    Objective-C中NSArray的基本用法示例
    UIImageView的图片居中问题
    iOS UI基础-19.0 UICollectionView
  • 原文地址:https://www.cnblogs.com/stevenshushu/p/9225016.html
Copyright © 2011-2022 走看看