scrapy爬虫(一)——爬取小说

scrapy爬虫(一)——爬取小说

(一)建立项目

​ 建立一个文件夹,进入文件夹——进入cmd命令框创建项目

(c) 2018 Microsoft Corporation。保留所有权利。

C:\Users\张华超\Desktop\petzhang>python -m scrapy startproject petspider
New Scrapy project 'petspider', using template directory 'D:\软件\python3.7\lib\site-packages\scrapy\templates\project', created in:
    C:\Users\张华超\Desktop\petzhang\petspider

You can start your first spider with:
    cd petspider
    scrapy genspider example example.com

C:\Users\张华超\Desktop\petzhang>cd petspider

C:\Users\张华超\Desktop\petzhang\petspider>scrapy genspider petzhang purepen.com
Created spider 'petzhang' using template 'basic' in module:
  petspider.spiders.petzhang

(二)编写程序

# -*- coding: utf-8 -*-
import scrapy
#解析网页一下四种方法,选哪个都可以
import re
#from bs4 import BeautifulSoup
#from lxml import etree
#from parsel import Selector


#爬虫类 也是python中的类
class SsyySpider(scrapy.Spider):
    name = 'ssyy'#爬虫名字
    allowed_domains = ['purepen.com/']#网站
    start_urls = ['http://www.purepen.com/sgyy/index.htm']#第一次开始采集的网址

#start_urls采集的信息 返回的内容就交给了response
    def parse(self, response):
        #print(response.text)#打印网页的文本内容
        #通过正则 提取文本中所有符合的内容
        #.*?   匹配任何你需要的信息
        detailurl=re.findall('',response.text)
        #print(detailurl)
        #构造完整的网址
        for url in detailurl[:10]:
            #拼接网址(两个方法)
            url='http://www.purepen.com/sgyy/%s' % url
            #url=f'http://www.purepen.com/sgyy/{url}'
            print(url)
            #发出请求 获取详情页信息
            yield scrapy.Request(url,callback=self.parseDetail,dont_filter=True)#dont_filter=True  停用过滤功能(你要request的地址和allow_domain里面的冲突,从而被过滤掉。可以停用过滤功能。)
            
    def parseDetail(self, response):
        #提取详情页数据
        text=re.findall('(.*?)',response.text,re.S)
        title=re.findall('(.*?)',response.text,re.S)
        #print(text)
        if text and title:
            self.save2File(title[0],text[0])
            
    #将爬取的信息写入文本
    @classmethod
    def save2File(cls,title,text):
        with open(f'{title}.txt','a',encoding='utf-8') as fp:
            fp.write(text)

你可能感兴趣的:(scrapy爬虫(一)——爬取小说)