使用scrapy来抓取 ChinaPub 这个网站上的图片_并且将其下载到本地

1.首先我们使用  scrapy startproject chinapub  这个命令来创建出一个scrapy项目,创建完毕之后scrapy的目录结构如下图所示:


2.在spider目录下新建一个 chinapub.py的文件,并且编写上下面的代码.

# -*- coding: utf-8 -*-
import scrapy

from scrapy.spider import Spider
from scrapy.selector import Selector
from chinapub.items import ChinapubItem
import urllib
from urllib import request

import sys
import os

class ReadbookSpider(scrapy.Spider):
    name = "readbook"
    allowed_domains = ["http://www.china-pub.com/"]
    #start_urls = ['https://www.dushu.com/book/']
    start_urls = ['http://product.china-pub.com/cache/rank3/onlinecenter.html']



    def parse(self, response):
        selector = Selector(response)    #创建选择器

        imgs_path = sys.path[0]+"/imgs/"
        #xpath的方式来提取出页面想要内容的信息
        imgs = selector.xpath("//div[@class='tjyd']/ul/li/a/img/@file").extract()

        #for imgpath in imgs:

        for index in range(len( imgs )):

                print(imgs[index])

                response = request.urlopen(imgs[index])
                binary_data = response.read()
                temp_file = open(  imgs_path+str(index)+'.jpg','wb' )
                temp_file.write(binary_data)
                temp_file.close()

                #urllib.urlretrieve(imgpath,"F:/imgs/1.jpg")

        pass

3.在项目的根目录下新建一个 imgs 这样名字的一个文件夹如下图
4.在项目的根目录下创建一个main.py这样的文件,编写上下面的代码 
# -*- coding: utf-8 -*-
__author__ = 'bobby'

from scrapy.cmdline import execute

import sys
import os


sys.path.append(os.path.dirname(os.path.abspath(__file__)))   #获取到当前整个工程  ArticleSpider这个项目的目录路径  os.path.dirname  这个函数指的是当前这个文件路径,os.path.dirname指的是某个目录的父级别路径

execute(["scrapy","crawl","readbook"])

# #sys.path.append("F:\scrapy_project\ArticleSpider")

5.运行主程序文件
结果就把
http://product.china-pub.com/cache/rank3/onlinecenter.html   url下的所有文件全部都爬取下来了
效果如下图所示:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值