爬蟲系列一之爬取旅游網(wǎng)站圖片

前言

接下來(lái)的一段時(shí)間里,將完成一個(gè)爬蟲系列文章,各位請(qǐng)慢慢看,也請(qǐng)慢慢點(diǎn)贊
這一節(jié)先講講大致工具和目標(biāo)吧

1 目標(biāo)和工具

作為菜鳥先從爬圖片入手吧,下手目標(biāo)就是 <a >螞蜂窩旅游網(wǎng)站</a>
爬蟲工具用我們的老朋友scrapy
配置python版本用 virtualenv 比較方便使用
命令

virtualenv -p c:\Python36\python.exe HigEnv #windows7

2 基本步驟

1.創(chuàng)建scrapy工程

cmd cd到合適目錄下,輸入命令

scrapy startproject mafengwoscrapy

這樣就在當(dāng)前目錄下創(chuàng)建了mafengwoscrapy這個(gè)工程

2.創(chuàng)建一個(gè)spider

在mafengwoscrapy工程下的spiders 目錄下創(chuàng)建一個(gè) mafengwospider.py文件
注釋寫的比較清楚可以直接看

# -*- coding: utf-8 -*-
import os
import urllib
from queue import Queue
from urllib import request
import scrapy
from scrapy import Selector, Request
import re


class MafengwospiderSpider(scrapy.Spider):
    name = 'mafengwospider'
    #開始爬取的網(wǎng)站
    start_urls = ['http://www.mafengwo.cn/mdd/']
    code_citymap = {}

    def parse(self, response):
        if response.url == 'http://www.mafengwo.cn/mdd/':
            #這是根據(jù)頁(yè)面的來(lái)進(jìn)行xpath匹配
            #這一步的目的是爬取mafengwo網(wǎng)站所有的國(guó)內(nèi)城市和對(duì)應(yīng)的code
            extract = response.xpath("http://div[@class='hot-list clearfix']").xpath(".//a").extract()
            #正則表達(dá)式提取城市code
            pattern = re.compile(r"/(\d*?).html")
            for ahtmltext in extract:
                #將html格式的字符串進(jìn)行xpath篩選的方法
                code_place = Selector(text=ahtmltext).xpath("http://a/@href|//a/text()").extract()
                if len(code_place) == 2:
                    code = pattern.findall(code_place[0])
                    self.code_citymap[code[0]] = code_place[1]
            print(self.code_citymap)
            #將城市code放入隊(duì)列
            #采取深度優(yōu)先的策略爬取
            self.codes = Queue()
            for a in self.code_citymap.keys():
                self.codes.put(a)
            citycode = self.codes.get()
            #注意下,這個(gè)http://www.mafengwo.cn/yj/%s/1-0-1.html的url是mafengwo網(wǎng)站每一個(gè)城市的游記列表的入口
            #meta用來(lái)標(biāo)識(shí)請(qǐng)求來(lái)源和請(qǐng)求額外參數(shù)很方便
            yield Request(url=r"http://www.mafengwo.cn/yj/%s/1-0-1.html" % (citycode),
                          meta={"code": citycode, "type": "list"})
            ##判斷請(qǐng)求是城市游記文章列表頁(yè)
        elif response.meta["type"] == "list":
            code = response.meta["code"]
            if 'pageindex' not in response.meta:
                pageindex = 1;
            else:
                pageindex = response.meta["pageindex"]
            pageindex += 1
            #這個(gè)xpath能篩選出該頁(yè)所有的文章信息
            extract = response.xpath(
                r"http://li[@class='post-item clearfix']/div[@class='post-cover']/a/@href"
            ).extract()
            if len(extract) > 0:
                #爬取分頁(yè)中的每一篇文章
                for followurl in extract:
                    yield response.follow(url=followurl, priority=20,
                                          meta={"code": code, "type": "article"})
                #每個(gè)城市只爬到第2頁(yè)
                if (pageindex <=2):
                    yield response.follow(
                        url="http://www.mafengwo.cn/yj/%s/1-0-%s.html" % (code, pageindex),
                        priority=10,meta={"code": code, "type": "list", "pageindex": pageindex}
                    )
                #爬下一個(gè)城市
                elif not self.codes.empty():
                    citycode = self.codes.get()
                    yield Request(url=r"http://www.mafengwo.cn/yj/%s/1-0-1.html" % (citycode),
                                  meta={"code": citycode, "type": "list"})
            #當(dāng)前城市返回空,爬下一個(gè)城市
            elif not self.codes.empty():
                citycode = self.codes.get()
                yield Request(url=r"http://www.mafengwo.cn/yj/%s/1-0-1.html" % (citycode),
                              meta={"code": citycode, "type": "list"})
                #判斷請(qǐng)求的是文章詳情頁(yè)
        elif response.meta["type"] == "article":
            code = response.meta["code"]
            htmlname = response.url.split("/")[-1].replace(r".html", "")
            #提取出該文章中所有的圖片鏈接
            images = response.xpath(
                "http://img[@class='_j_lazyload _j_needInitShare']/@data-src").extract()
            if len(images) == 0:
                print(htmlname + " failed")
            for i in range(len(images)):
                #所有圖片下載到本地
                print(images[i])
                filedir = "E:/images/mafengwo/%s" % (self.code_citymap[code])
                if not os.path.exists(filedir):
                    os.makedirs(filedir)
                imagefilepath="%s/%s_%s.jpg" % (filedir, htmlname, i)
                if not os.path.exists(imagefilepath):
                    #python3 urllib下載簡(jiǎn)單圖片或者文件的方法
                    req=urllib.request.Request(images[i])
                    with urllib.request.urlopen(req,timeout=10) as f:
                        with open(imagefilepath,"wb") as writef:
                            writef.write(f.read())

整體的爬蟲代碼需要結(jié)合網(wǎng)頁(yè)的源碼看,沒什么細(xì)節(jié)的就不多說(shuō)了,另外在工程目錄
的settings.py中,改下參數(shù)


# 設(shè)置為不遵守robot協(xié)議
#以及每次scrapy request 請(qǐng)求最小間隔為1s,防止被反爬蟲
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 1
3.啟動(dòng)爬蟲

爬蟲啟動(dòng)很簡(jiǎn)單的,cd 到 mafengwoscrapy工程目錄下執(zhí)行

scrapy crawl mafengwospider 即可
4.結(jié)果

爬取的速度不是很快,結(jié)果如截圖所示


城市列表.png

城市里面的游記.png
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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