1. 程式人生 > 實用技巧 >使用scrapy爬取jian shu文章

使用scrapy爬取jian shu文章

settings.py中一些東西的含義可以看一下這裡

python的scrapy框架的使用 和xpath的使用 && scrapy中request和response的函式引數 && parse()函式執行機制

目錄結構

一、使用scrapy的crawl模板來建立一個爬蟲jianshu.py檔案

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from js.items import JsItem

class JianshuSpider(CrawlSpider): # 執行scrapy時候的名字 name = 'jianshu' allowed_domains = ['jianshu.com'] start_urls = ['https://www.jianshu.com'] rules = ( # 要爬取網頁上的推薦文章,進而可以使用crawl爬取我們規定的連結 # 網頁上的推薦文章連結是“/p/(12個【字母/數字】)” Rule(LinkExtractor(allow=r'.*?p/.*?
'), callback='parse_detail', follow=True), ) def parse_detail(self, response): # print(response.text()) # print('-'*30) passage_id = response.url title = response.xpath('//h1[@class="_1RuRku"]/text()').get() time = response.xpath('//div[@class="s-dsoj"]/time/text()
').get() author = response.xpath('//span[@class="FxYr8x"]/a/text()').get() body = response.xpath('//article[@class="_2rhmJa"]').get() type = response.xpath('//div[@class="_2Nttfz"]/a/img/text()').getall() type = ','.join(type) # 比如文章連結為https://www.jianshu.com/p/ef7bb28258c8 # 那麼文章的id,passage_id就是ef7bb28258c8,因為有的連結後面還有跟上“?引數”,所以我們先按照“?” # 切割連結,然後再取出文章id passage_id = passage_id.split('?')[0] passage_id = passage_id.split('/')[-1] # 有些文章違規在簡書上不能看,但是連結還存在,所以我們需要判斷一下 if author == None: pass else: # 只要返回的物件是item型別,無論在那個函式裡面返回都是返回到pipelines.py的item引數裡面 item = JsItem( passage_id = passage_id, title = title, time = time, author = author, body = body, type = type ) yield item

二、item.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy

# 定義一下Item的物件的一些變數
class JsItem(scrapy.Item):
    passage_id = scrapy.Field()
    title = scrapy.Field()
    time = scrapy.Field()
    author = scrapy.Field()
    body = scrapy.Field()
    type = scrapy.Field()

三、start.py (啟動程式)

from scrapy import cmdline
# jianshu是你的爬蟲程式檔案,注意要把這個命令用split拆開
cmdline.execute("scrapy crawl jianshu".split())

四、pipelines.py

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
from twisted.enterprise import adbapi
import pymysql

# class JsPipeline:
#     def process_item(self, item, spider):
#         return item

class JianShuSpiderPipeline(object):
    def __init__(self):
        # 連線資料庫的一些引數
        dpparams = {
            'host':'127.0.0.1',
            'port': 3306,
            'user':'root',
            'password':'your_password',
            'database':'jianshu',
            'charset':'utf8'
        }
        # 連線資料庫
        self.conn = pymysql.connect(**dpparams)
        # 定義遊標
        self.cursor = self.conn.cursor()
        self._sql = None

    @property # 定義屬性
    def sql(self):
        if self._sql == None:
            self._sql = '''
            insert into jsw(passage_id,title,time,author,body,type) values(%s,%s,%s,%s,%s,%s)
            '''
            return self._sql
        else:
            return self._sql

    def process_item(self,item,spider):
        # 執行sql語句,並傳參
        self.cursor.execute(self.sql,(item['passage_id'],item['title'],item['time'],item['author'],item['body'],item['type']))
        # 記得執行之後要提交
        self.conn.commit()
        # 必須返回,不返回就不會處理下一個item物件
        return item

# 異步向mysql中插入資料
# class JianShuTwistedPipeline:
#     def __init__(self):
#         dpparams = {
#             'host':'127.0.0.1',
#             'port': 3306,
#             'user':'root',
#             'password':'qu513712qu',
#             'database':'jianshu',
#             'charset':'utf-8'
#         }
#         self.dbpool = adbapi.Connection('pymysql',**dpparams)
#         self._sql = None
#
#     @property
#     def sql(self):
#         if self._sql == None:
#             self._sql = '''
#             insert into jsw values(%s,%s,%s,%s,%s,%s)
#             '''
#             return self._sql
#         else:
#             return self._sql
#
#     def process_item(self,item,spider):
#         # 把插入Insert函式放到runInteraction裡面,插入資料就會變成非同步的,如果直接執行函式就是非同步執行了
#         # runInteraction會返回一個遊標給Insert函式
#         defer = self.dbpool.runInteraction(self.Insert,item)
#         defer.addErrback(self.error,item,spider)
#
#     def Insert(self,cursor,item):
#         cursor.execute(self._sql,(item['passage_id'],item['title'],item['time'],item['author'],item['body'],item['type']))
#
#     def error(self,error,item,spider):
#         print('-'*30)
#         print('error')
#         print('-'*30)

五、setting.py

# Scrapy settings for js project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'js'

SPIDER_MODULES = ['js.spiders']
NEWSPIDER_MODULE = 'js.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'js (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = 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',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'

}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
    # 'js.middlewares.JsSpiderMiddleware': 543,
   'js.middlewares.UserAgentMiddleWare': 543,
}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   # 'js.middlewares.JsDownloaderMiddleware': 543,
   'js.middlewares.SeleniumDownloadMiddleware': 543,
}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    # 管道里面使用的儲存資料的類
   'js.pipelines.JianShuSpiderPipeline': 300,
   # 'js.pipelines.JianShuTwistedPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

六、middlewares.py

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
import random
from selenium import webdriver
import time
from scrapy.http.response.html import HtmlResponse

class JsSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class JsDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class UserAgentMiddleWare:
    User_Agent = [
        "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
        "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
        "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
        "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
        "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
        "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
        "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

    ]
    def process_request(self,request,spider):
        user_agent = random.choice(self.User_Agent)
        request.headers['User-Agent'] = user_agent


class SeleniumDownloadMiddleware(object):
    # 通過selenium+chrome來爬取網頁的一些動態載入的資料
    def __init__(self): # 將你的chrome.exe檔案位置傳給它
        self.driver = webdriver.Chrome(executable_path=r'D:\python-senium\chromedriver.exe')

    def process_request(self,request,spider):
        self.driver.get(request.url)
        time.sleep(2)
        try:
            while 1:  # 文章下面有文章分類,我們需要點選載入載入更多才可以找出來這篇文章的所有歸屬型別
                showmore = self.driver.find_element_by_class_name('anticon anticon-down')
                showmore.click()
                time.sleep(1)
                if not showmore:
                    break
        except:
            pass
        # 網頁原始碼
        sourse = self.driver.page_source
        # 構造一個response物件,並返回給jianshu.py
        response = HtmlResponse(url=self.driver.current_url,body=sourse,request=request,encoding='utf-8')
        return response