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 TodayScrapyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass class TuchongItem(scrapy.Item):
title = scrapy.Field() #图片名字
views = scrapy.Field() #浏览人数
favorites = scrapy.Field()#点赞人数
img_url = scrapy.Field()#图片地址 # def get_insert_sql(self):
# # 存储时候用的sql语句
# sql = 'insert into tuchong(title,views,favorites,img_url)' \
# ' VALUES (%s, %s, %s, %s)'
# # 存储的数据
# data = (self['title'], self['views'], self['favorites'], self['img_url'])
# return (sql, data)

setting.py 设置headers和items

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

# Scrapy settings for today_scrapy project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'today_scrapy' SPIDER_MODULES = ['today_scrapy.spiders']
NEWSPIDER_MODULE = 'today_scrapy.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'today_scrapy (+http://www.yourdomain.com)' # 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://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',
'User-Agnet':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
} # Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'today_scrapy.middlewares.TodayScrapySpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'today_scrapy.middlewares.TodayScrapyDownloaderMiddleware': 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 = {
# 'today_scrapy.pipelines.TodayScrapyPipeline': 300,
'today_scrapy.pipelines.TuchongPipeline': 200, } # 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'

pipelines.py 将图片下载到指定文件夹

 # -*- 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
import requests class TodayScrapyPipeline(object):
def process_item(self, item, spider):
return item class TuchongPipeline(object):
def process_item(self, item, spider):
img_url = item['img_url'] #从items中得到图片url地址
img_title= item['title'] #得到图片的名字
headers = {
'User-Agnet': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'cookie':'webp_enabled=1; bad_ide7dfc0b0-b3b6-11e7-b58e-df773034efe4=78baed41-a870-11e8-b7fd-370d61367b46; _ga=GA1.2.1188216139.1535263387; _gid=GA1.2.1476686092.1535263387; PHPSESSID=4k7pb6hmkml8tjsbg0knii25n6'
}
if not os.path.exists(img_title):
os.mkdir(img_title)
filename =img_url.split('/')[-1]
with open(img_title+'/'+filename, 'wb+') as f:
f.write(requests.get(img_url, headers=headers).content)
f.close()
return item

爬虫文件

tuchong.py

图片的url可以直接拼接

 # -*- coding: utf-8 -*-
import scrapy
import json
from today_scrapy.items import TuchongItem class TuchongSpider(scrapy.Spider):
name = 'tuchong'
allowed_domains = ['tuchong.com']
start_urls = ['http://tuchong.com/'] def start_requests(self):
for pag in range(1, 20):
referer_url = 'https://tuchong.com/rest/tags/自然/posts?page={}&count=20'.format(pag) # url中红字部分可以换
form_req = scrapy.Request(url=referer_url, callback=self.parse)
form_req.headers['referer'] = referer_url
yield form_req def parse(self, response):
tuchong_info_html = json.loads(response.text)
# print(tuchong_info_html)
postList_c = len(tuchong_info_html['postList'])
# print(postList_c)
for c in range(postList_c):
print(c)
# print(tuchong_info_html['postList'][c])
title = tuchong_info_html['postList'][c]['title']
print('图集名称:'+title)
views = tuchong_info_html['postList'][c]['views']
print('有'+str(views)+'人浏览')
favorites = tuchong_info_html['postList'][c]['favorites']
print('喜欢的人数:'+str(favorites))
images_c = len(tuchong_info_html['postList'][c]['images'])
for img_c in range(images_c):
user_id = tuchong_info_html['postList'][c]['images'][img_c]['user_id']
img_id = tuchong_info_html['postList'][c]['images'][img_c]['img_id']
img_url = 'https://photo.tuchong.com/{}/f/{}.jpg'.format(user_id,img_id)
item = TuchongItem()
item['title'] = title
item['img_url'] = img_url
# 返回我们的item
yield item

爬虫 Scrapy框架 爬取图虫图片并下载的更多相关文章

  1. python爬虫scrapy框架——爬取伯乐在线网站文章

    一.前言  1. scrapy依赖包: 二.创建工程 1. 创建scrapy工程: scrapy staratproject ArticleSpider 2. 开始(创建)新的爬虫: cd Artic ...

  2. python3爬虫-通过requests爬取图虫网

    import requests from fake_useragent import UserAgent from requests.exceptions import Timeout from ur ...

  3. 使用scrapy框架爬取自己的博文(2)

    之前写了一篇用scrapy框架爬取自己博文的博客,后来发现对于中文的处理一直有问题- - 显示的时候 [u'python\u4e0b\u722c\u67d0\u4e2a\u7f51\u9875\u76 ...

  4. scrapy框架爬取糗妹妹网站妹子图分类的所有图片

    爬取所有图片,一个页面的图片建一个文件夹.难点,图片中有不少.gif图片,需要重写下载规则, 创建scrapy项目 scrapy startproject qiumeimei 创建爬虫应用 cd qi ...

  5. 使用scrapy框架爬取图片网全站图片(二十多万张),并打包成exe可执行文件

    目标网站:https://www.mn52.com/ 本文代码已上传至git和百度网盘,链接分享在文末 网站概览 目标,使用scrapy框架抓取全部图片并分类保存到本地. 1.创建scrapy项目 s ...

  6. python 爬虫入门----案例爬取上海租房图片

    前言 对于一个net开发这爬虫真真的以前没有写过.这段时间学习python爬虫,今天周末无聊写了一段代码爬取上海租房图片,其实很简短就是利用爬虫的第三方库Requests与BeautifulSoup. ...

  7. scrapy框架爬取笔趣阁完整版

    继续上一篇,这一次的爬取了小说内容 pipelines.py import csv class ScrapytestPipeline(object): # 爬虫文件中提取数据的方法每yield一次it ...

  8. scrapy框架爬取笔趣阁

    笔趣阁是很好爬的网站了,这里简单爬取了全部小说链接和每本的全部章节链接,还想爬取章节内容在biquge.py里在加一个爬取循环,在pipelines.py添加保存函数即可 1 创建一个scrapy项目 ...

  9. 爬虫入门(四)——Scrapy框架入门:使用Scrapy框架爬取全书网小说数据

    为了入门scrapy框架,昨天写了一个爬取静态小说网站的小程序 下面我们尝试爬取全书网中网游动漫类小说的书籍信息. 一.准备阶段 明确一下爬虫页面分析的思路: 对于书籍列表页:我们需要知道打开单本书籍 ...

随机推荐

  1. js的一道经典题目

    今天碰到一道题,里面既包含了匿名函数的知识,也包含了预编译,函数的传参(形参),感觉迷迷糊糊的,所以想着做个总结. var foo={n:1}; (function(foo){ console.log ...

  2. update from select

    CREATE TABLE dualx( x_id ) NOT NULL , x_con ) ) CREATE TABLE dualy( y_id ) NOT NULL , y_con ) ) ','x ...

  3. Maven编译Java程序配置

    Hive 需要在工程里添加的Jar包: hadoop-2.2.0/share/hadoop/common/hadoop-common-2.2.0.jar $HIVE_HOME/lib/hive-exe ...

  4. Xposed模块开发基本方法记录

    由于某些课程实验的要求,需要通过xposed框架对某应用进行hook操作,笔者选用了开源且免费的xposed框架进行实现.虽然网上存在一些利用xposed实现特定功能的文章资源,但大多均将xposed ...

  5. BZOJ1731:[USACO]Layout 排队布局(差分约束)

    Description Like everyone else, cows like to stand close to their friends when queuing for feed. FJ ...

  6. luogu P3381【模板】最小费用最大流

    嘟嘟嘟 没错,我开始学费用流了! 做法也是比较朴素的\(spfa\). 就是每一次以费用为权值跑一遍\(spfa\)找到一条最短路,然后把这条道全流满,并把这一次的流量和费用累加到答案上.因此我们需要 ...

  7. sudo 启动tomcat报错没有java环境

    报错: Cannot find ./catalina.shThe file is absent or does not have execute permissionThis file is need ...

  8. 知乎TensorFlow入门学习记录

    知乎地址:https://zhuanlan.zhihu.com/p/30487008 import tensorflow as tf a=tf.placeholder(tf.int16) # 接受的数 ...

  9. Python 自动化paramiko操作linux使用shell命令,以及文件上传下载linux与windows之间的实现

    # coding=utf8 import paramiko """ /* python -m pip install paramiko python version 3. ...

  10. Dubbo实践(十三)Export

    Spring在启动Dubbo服务端应用时,会实例化ServiceBean<T>并设置配置属性,然后调用export方法: @SuppressWarnings({"unchecke ...