Scrapy 中 CrawlSpider 使用(二)

 LinkExtractor提取链接

创建爬虫

scrapy genspider 爬虫名 域名 -t crawl

spider

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class XsSpider(CrawlSpider):
    name = "爬虫名"
    allowed_domains = ["域名"]
    start_urls = ["首页url地址"]

    # rules = (Rule(LinkExtractor(restrict_xpaths='//*[@id="list"]/dl/dd[10]/a'), callback="parse_item", follow=True),)
    rules = (
        # 获取第一章链接
        Rule(LinkExtractor(restrict_xpaths='//div[@id="list"]/dl/dd[10]/a'), callback="parse_item", follow=True),
        # 获取下一章链接
        Rule(LinkExtractor(restrict_xpaths='//div[@class="bottem2"]/a[4]'), callback="parse_item", follow=True),
        )

    def parse_item(self, response):
        # 章节名称
        title = response.xpath('//h1/text()').get()     #extract_first()
        # 章节内容
        content = response.xpath('//div[@id="content"]/text()').getall()   #extract()

        yield {
            'title':title,
            'content':content
        }

直接爬取可能会忽略掉第一章,所以要单独获取第一章的url 

pipeline

class Scrapy05Pipeline:
    def open_spider(self,spider):
        self.file = open('文件名.txt','w',encoding='utf-8')
    def process_item(self, item, spider):
        self.file.write(item['title']+'\n')
        self.file.write(''.join(item['content'])+'\n\n\n\n')
        return item
    def close_spider(self,spider):
        self.file.close()

begin

执行命令scrapy crawl 爬虫名

from scrapy.cmdline import execute

execute(['scrapy','crawl','爬虫名'])

 

posted @   jiang_jiayun  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示