最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python 詳解通過(guò)Scrapy框架實(shí)現(xiàn)爬取CSDN全站熱榜標(biāo)題熱詞流程

 更新時(shí)間:2021年11月10日 10:48:59   作者:劍客阿良_ALiang  
Scrapy是用純Python實(shí)現(xiàn)一個(gè)為了爬取網(wǎng)站數(shù)據(jù)、提取結(jié)構(gòu)性數(shù)據(jù)而編寫(xiě)的應(yīng)用框架,用途非常廣泛,框架的力量,用戶只需要定制開(kāi)發(fā)幾個(gè)模塊就可以輕松的實(shí)現(xiàn)一個(gè)爬蟲(chóng),用來(lái)抓取網(wǎng)頁(yè)內(nèi)容以及各種圖片,非常之方便

前言

接著我的上一篇:Python 詳解爬取并統(tǒng)計(jì)CSDN全站熱榜標(biāo)題關(guān)鍵詞詞頻流程

我換成Scrapy架構(gòu)也實(shí)現(xiàn)了一遍。獲取頁(yè)面源碼底層原理是一樣的,Scrapy架構(gòu)更系統(tǒng)一些。下面我會(huì)把需要注意的問(wèn)題,也說(shuō)明一下。

提供一下GitHub倉(cāng)庫(kù)地址:github本項(xiàng)目地址

環(huán)境部署

scrapy安裝

pip install scrapy -i https://pypi.douban.com/simple

selenium安裝

pip install selenium -i https://pypi.douban.com/simple

jieba安裝

pip install jieba -i https://pypi.douban.com/simple

IDE:PyCharm

google chrome driver下載對(duì)應(yīng)版本:google chrome driver下載地址

檢查瀏覽器版本,下載對(duì)應(yīng)版本。

實(shí)現(xiàn)過(guò)程

下面開(kāi)始搞起。

創(chuàng)建項(xiàng)目

使用scrapy命令創(chuàng)建我們的項(xiàng)目。

scrapy startproject csdn_hot_words

項(xiàng)目結(jié)構(gòu),如同官方給出的結(jié)構(gòu)。

定義Item實(shí)體

按照之前的邏輯,主要屬性為標(biāo)題關(guān)鍵詞對(duì)應(yīng)出現(xiàn)次數(shù)的字典。代碼如下:

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
 
import scrapy
 
 
class CsdnHotWordsItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    words = scrapy.Field()

關(guān)鍵詞提取工具

使用jieba分詞獲取工具。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/5 23:47
# @Author  : 至尊寶
# @Site    : 
# @File    : analyse_sentence.py
 
import jieba.analyse
 
 
def get_key_word(sentence):
    result_dic = {}
    words_lis = jieba.analyse.extract_tags(
        sentence, topK=3, withWeight=True, allowPOS=())
    for word, flag in words_lis:
        if word in result_dic:
            result_dic[word] += 1
        else:
            result_dic[word] = 1
    return result_dic

爬蟲(chóng)構(gòu)造

這里需要給爬蟲(chóng)初始化一個(gè)瀏覽器參數(shù),用來(lái)實(shí)現(xiàn)頁(yè)面的動(dòng)態(tài)加載。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/5 23:47
# @Author  : 至尊寶
# @Site    : 
# @File    : csdn.py
 
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
 
from csdn_hot_words.items import CsdnHotWordsItem
from csdn_hot_words.tools.analyse_sentence import get_key_word
 
 
class CsdnSpider(scrapy.Spider):
    name = 'csdn'
    # allowed_domains = ['blog.csdn.net']
    start_urls = ['https://blog.csdn.net/rank/list']
 
    def __init__(self):
        chrome_options = Options()
        chrome_options.add_argument('--headless')  # 使用無(wú)頭谷歌瀏覽器模式
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--no-sandbox')
        self.browser = webdriver.Chrome(chrome_options=chrome_options,
                                        executable_path="E:\\chromedriver_win32\\chromedriver.exe")
        self.browser.set_page_load_timeout(30)
 
    def parse(self, response, **kwargs):
        titles = response.xpath("http://div[@class='hosetitem-title']/a/text()")
        for x in titles:
            item = CsdnHotWordsItem()
            item['words'] = get_key_word(x.get())
            yield item

代碼說(shuō)明

1、這里使用的是chrome的無(wú)頭模式,就不需要有個(gè)瀏覽器打開(kāi)再訪問(wèn),都是后臺(tái)執(zhí)行的。

2、需要添加chromedriver的執(zhí)行文件地址。

3、在parse的部分,可以參考之前我文章的xpath,獲取到標(biāo)題并且調(diào)用關(guān)鍵詞提取,構(gòu)造item對(duì)象。

中間件代碼構(gòu)造

添加js代碼執(zhí)行內(nèi)容。中間件完整代碼:

# 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
from scrapy.http import HtmlResponse
from selenium.common.exceptions import TimeoutException
import time
 
from selenium.webdriver.chrome.options import Options
 
# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
 
 
class CsdnHotWordsSpiderMiddleware:
    # 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 CsdnHotWordsDownloaderMiddleware:
    # 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):
        js = '''
                        let height = 0
                let interval = setInterval(() => {
                    window.scrollTo({
                        top: height,
                        behavior: "smooth"
                    });
                    height += 500
                }, 500);
                setTimeout(() => {
                    clearInterval(interval)
                }, 20000);
            '''
        try:
            spider.browser.get(request.url)
            spider.browser.execute_script(js)
            time.sleep(20)
            return HtmlResponse(url=spider.browser.current_url, body=spider.browser.page_source,
                                encoding="utf-8", request=request)
        except TimeoutException as e:
            print('超時(shí)異常:{}'.format(e))
            spider.browser.execute_script('window.stop()')
        finally:
            spider.browser.close()
 
    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)

制作自定義pipeline

定義按照詞頻統(tǒng)計(jì)最終結(jié)果輸出到文件。代碼如下:

# 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
 
 
class CsdnHotWordsPipeline:
 
    def __init__(self):
        self.file = open('result.txt', 'w', encoding='utf-8')
        self.all_words = []
 
    def process_item(self, item, spider):
        self.all_words.append(item)
        return item
 
    def close_spider(self, spider):
        key_word_dic = {}
        for y in self.all_words:
            print(y)
            for k, v in y['words'].items():
                if k.lower() in key_word_dic:
                    key_word_dic[k.lower()] += v
                else:
                    key_word_dic[k.lower()] = v
        word_count_sort = sorted(key_word_dic.items(),
                                 key=lambda x: x[1], reverse=True)
        for word in word_count_sort:
            self.file.write('{},{}\n'.format(word[0], word[1]))
        self.file.close()

settings配置

配置上要做一些調(diào)整。如下調(diào)整:

# Scrapy settings for csdn_hot_words 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 = 'csdn_hot_words'
 
SPIDER_MODULES = ['csdn_hot_words.spiders']
NEWSPIDER_MODULE = 'csdn_hot_words.spiders'
 
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# USER_AGENT = 'csdn_hot_words (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0'
 
# 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 = 30
# 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 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
}
 
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
   'csdn_hot_words.middlewares.CsdnHotWordsSpiderMiddleware': 543,
}
 
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'csdn_hot_words.middlewares.CsdnHotWordsDownloaderMiddleware': 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 = {
    'csdn_hot_words.pipelines.CsdnHotWordsPipeline': 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'

執(zhí)行主程序

可以通過(guò)scrapy的命令執(zhí)行,但是為了看日志方便,加了一個(gè)主程序代碼。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/5 22:41
# @Author  : 至尊寶
# @Site    : 
# @File    : main.py
from scrapy import cmdline
 
cmdline.execute('scrapy crawl csdn'.split())

執(zhí)行結(jié)果

執(zhí)行部分日志

得到result.txt結(jié)果。

總結(jié)

看,java還是yyds。不知道為什么2021這個(gè)關(guān)鍵詞也可以排名靠前。于是我覺(jué)著把我標(biāo)題也加上2021。

GitHub項(xiàng)目地址在發(fā)一遍:github本項(xiàng)目地址

申明一下,本文案例僅研究探索使用,不是為了惡意攻擊。

分享:

凡夫俗子不下苦功夫、死力氣去努力做成一件事,根本就沒(méi)資格去談什么天賦不天賦。

——烽火戲諸侯《劍來(lái)》

如果本文對(duì)你有用的話,請(qǐng)不要吝嗇你的贊,謝謝。

以上就是Python 詳解通過(guò)Scrapy框架實(shí)現(xiàn)爬取CSDN全站熱榜標(biāo)題熱詞流程的詳細(xì)內(nèi)容,更多關(guān)于Python Scrapy框架的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python pytesseract驗(yàn)證碼識(shí)別庫(kù)用法解析

    Python pytesseract驗(yàn)證碼識(shí)別庫(kù)用法解析

    這篇文章主要介紹了Python pytesseract驗(yàn)證碼識(shí)別庫(kù)用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • django 實(shí)現(xiàn)簡(jiǎn)單的插入視頻

    django 實(shí)現(xiàn)簡(jiǎn)單的插入視頻

    這篇文章主要介紹了django 實(shí)現(xiàn)簡(jiǎn)單的插入視頻,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • python多線程超詳細(xì)詳解

    python多線程超詳細(xì)詳解

    這篇文章主要介紹了python多線程超詳細(xì)詳解,多線程這個(gè)知識(shí)點(diǎn)非常重要,想了解的同學(xué)可以參考下
    2021-04-04
  • python使用 cx_Oracle 模塊進(jìn)行查詢操作示例

    python使用 cx_Oracle 模塊進(jìn)行查詢操作示例

    這篇文章主要介紹了python使用 cx_Oracle 模塊進(jìn)行查詢操作,結(jié)合實(shí)例形式分析了Python使用cx_Oracle模塊進(jìn)行數(shù)據(jù)庫(kù)的基本連接、查詢、輸出等相關(guān)操作技巧,需要的朋友可以參考下
    2019-11-11
  • 用python實(shí)現(xiàn)學(xué)生管理系統(tǒng)

    用python實(shí)現(xiàn)學(xué)生管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了用python實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • Python實(shí)現(xiàn)的爬取網(wǎng)易動(dòng)態(tài)評(píng)論操作示例

    Python實(shí)現(xiàn)的爬取網(wǎng)易動(dòng)態(tài)評(píng)論操作示例

    這篇文章主要介紹了Python實(shí)現(xiàn)的爬取網(wǎng)易動(dòng)態(tài)評(píng)論操作,結(jié)合實(shí)例形式分析了Python針對(duì)網(wǎng)易評(píng)論正則爬取及json格式數(shù)據(jù)轉(zhuǎn)換、提取等相關(guān)操作技巧,需要的朋友可以參考下
    2018-06-06
  • python中如何以空格為分割符,給列表賦予數(shù)值

    python中如何以空格為分割符,給列表賦予數(shù)值

    這篇文章主要介紹了python中如何以空格為分割符,給列表賦予數(shù)值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Python中擴(kuò)展包的安裝方法詳解

    Python中擴(kuò)展包的安裝方法詳解

    這篇文章主要給大家總結(jié)了關(guān)于Python中擴(kuò)展包的安裝方法,文中介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編一起來(lái)學(xué)習(xí)學(xué)習(xí)吧。
    2017-06-06
  • python?字典常用方法超詳細(xì)梳理總結(jié)

    python?字典常用方法超詳細(xì)梳理總結(jié)

    這篇文章主要介紹了Python數(shù)據(jù)類型字典dictionary,字典是另一種可變?nèi)萜髂P?,且可存?chǔ)任意類型對(duì)象。本篇文字將詳細(xì)講述字典的常用方法,需要的可以參考一下
    2022-03-03
  • Python利用OpenCV和skimage實(shí)現(xiàn)圖像邊緣檢測(cè)

    Python利用OpenCV和skimage實(shí)現(xiàn)圖像邊緣檢測(cè)

    提取圖片的邊緣信息是底層數(shù)字圖像處理的基本任務(wù)之一。本文將通過(guò)OpenCV和skimage的?Canny?算法實(shí)現(xiàn)圖像邊緣檢測(cè),感興趣的可以了解一下
    2022-12-12

最新評(píng)論

共和县| 禄丰县| 临沭县| 陆良县| 邛崃市| 黄龙县| 扬州市| 吉安县| 民县| 卫辉市| 水城县| 藁城市| 宝清县| 锦州市| 延安市| 沾益县| 廉江市| 梅州市| 武鸣县| 潮州市| 仁寿县| 克拉玛依市| 临江市| 遂川县| 星子县| 南通市| 左云县| 金门县| 永康市| 万全县| 岗巴县| 东乌珠穆沁旗| 曲周县| 甘孜| 星子县| 青河县| 社会| 烟台市| 平山县| 彰武县| 富阳市|