Scrapy爬取爐石傳說原畫實(shí)踐

前言:

本文章適用于在Pycharm上使用Scrapy爬取爐石傳說原畫。

思路:

爐石傳說原畫網(wǎng)址

真相是假

當(dāng)我們打開開發(fā)者工具發(fā)現(xiàn),并不需要模擬點(diǎn)擊“點(diǎn)擊查看更多”,而是被display:none所隱藏
因此我們只要獲取所有的<li></li>標(biāo)簽即可
真相是真

$x('//*[@id="dq_list"]/li')  //獲取所有的li標(biāo)簽

Chrome xpath

最后只需要獲取<img>下的src內(nèi)容 以及 div class="kp-name"的內(nèi)容即可
item 分析

代碼準(zhǔn)備:

快速構(gòu)建一個(gè)scrapy項(xiàng)目

scrapy startproject lushichuanshuo
項(xiàng)目目錄結(jié)構(gòu)

items.py (爬取字段)

# -*- coding: utf-8 -*-

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

import scrapy


class LushichuanshuoItem(scrapy.Item):
    img = scrapy.Field()
    name = scrapy.Field()

pipelines.py (管道 存放驗(yàn)證數(shù)據(jù))

# -*- coding: utf-8 -*-

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

import os


class LushichuanshuoPipeline(object):
    def process_item(self, item, spider):
        file = open(os.path.dirname(__file__) + '/data/lushi1.txt', "a", encoding='utf-8')
        item_string = str(item)
        file.write(item_string)
        file.write('\n')
        file.close()
        return item


    def close_spider(self, spider):
        # 關(guān)閉爬蟲時(shí)順便將文件保存退出
        self.file.close()

settings.py (配置文件)


BOT_NAME = 'lushichuanshuo'

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

ITEM_PIPELINES = {
    'lushichuanshuo.pipelines.LushichuanshuoPipeline': 100,
}

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'lushichuanshuo (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# 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://doc.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',
#}

# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'lushichuanshuo.middlewares.LushichuanshuoSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'lushichuanshuo.middlewares.LushichuanshuoDownloaderMiddleware': 543,
#}

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

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
#    'lushichuanshuo.pipelines.LushichuanshuoPipeline': 300,
#}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.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://doc.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'

lushispider1.py (爬蟲文件)

import scrapy
from lushichuanshuo.items import LushichuanshuoItem


class DoubanshuSpiderSpider(scrapy.Spider):
    name = "lushichuanshuo_spider1"
    start_urls = (
        'http://news.4399.com/gonglue/lscs/kptj/',
    )
    def parse(self, response):
        sel = scrapy.Selector(response)
        illustrates = sel.xpath('//*[@id="dq_list"]/li')
        item = LushichuanshuoItem()
        for each in illustrates:
            img = each.xpath('a/img/@lz_src').extract()  //這里根據(jù)網(wǎng)頁得到的內(nèi)容用@lz_src替代@src
            name = each.xpath('a/div/text()').extract()
            item['img'] = img
            item['name'] = name
            yield item
        # next_page = sel.xpath('//*[@id="content"]/div/div[1]/div[31]/span[@class="next"]/a/@href').extract()
        # if next_page:
        #     next = next_page[0]
        #     yield scrapy.http.Request(next, callback=self.parse)

main.py (程序執(zhí)行處)


from scrapy import cmdline

cmdline.execute(["scrapy", "crawl", "lushichuanshuo_spider1"])  
//lushichuanshuo_spider1必須與lushispider1.py中的name一致

爬取數(shù)據(jù)

運(yùn)行main.py


運(yùn)行

發(fā)現(xiàn)800張?jiān)嬕呀?jīng)被我們爬取下來


成果展示

至此在Pycharm下使用Scrapy爬取第一個(gè)網(wǎng)頁的Demo已完成!

謝謝閱讀,有幫助的點(diǎn)個(gè)?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容