您的位置:首页 > 运维架构 > 网站架构

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

2018-01-08 10:03 597 查看
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下的所有文件全部都爬取下来了
效果如下图所示:

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: