#看到贴吧大佬在发图,准备盗一下

#只是爬取一个帖子中的图片

1、先新建一个scrapy项目

  scrapy startproject TuBaEx

2、新建一个爬虫

  scrapy genspider tubaex https://tieba.baidu.com/p/4092816277

3、先写下items

  #保存图片的url
  img_url=scrapy.Field()

4、开始写爬虫

  

# -*- coding: utf-8 -*-
import scrapy
from TuBaEx.items import TubaexItem class TubaexSpider(scrapy.Spider):
name = "tubaex"
#allowed_domains = ["https://tieba.baidu.com/p/4092816277"]
baseURL="https://tieba.baidu.com/p/4092816277?pn=" #拼接地址用 实现翻页
offset=0
#要爬取的网页
start_urls = [baseURL+str(offset)] def parse(self, response): #获取最后一页的数字
end_page=response.xpath("//div[@id='thread_theme_5']/div/ul/li[2]/span[2]/text()").extract()
#通过审查元素找到图片的类名,用xpath获取
img_list=response.xpath("//img[@class='BDE_Image']/@src").extract() for img in img_list:
item=TubaexItem()
item['img_url']=img
yield item url=self.baseURL #进行翻页
if self.offset < int(end_page[0]): #通过xpath返回的是list
self.offset+=1
yield scrapy.Request(self.baseURL+str(self.offset),callback=self.parse)

5、使用ImagesPipeline,这个没什么说的,我也不太懂

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

import requests
from scrapy.pipelines.images import ImagesPipeline
from TuBaEx import settings class TubaexPipeline(ImagesPipeline): def get_media_requests(self,item,info):
img_link = item['img_url']
yield scrapy.Request(img_link) def item_completed(self,results,item,info):
images_store="C:/Users/ll/Desktop/py/TuBaEx/Images/"
img_path=item['img_url']
return item

6、配置下settings

IMAGES_STORE = 'C:/Users/ll/Desktop/py/TuBaEx/Images/'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'TuBaEx (+http://www.yourdomain.com)'
USER_AGENT="User-Agent,Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
#开启管道
ITEM_PIPELINES = {
'TuBaEx.pipelines.TubaexPipeline': 300,
}

7、执行

  scrapy crawl tubaex

8、收获果实

  

最新文章

  1. mysql 安装问题
  2. Table
  3. javascript_core_01之数据类型与运算
  4. Oracle ASM diskgroup在主机重启后启动失败
  5. java栈和堆区别
  6. dbca no protocol support
  7. HTML a 标签 下载 apk 文件
  8. 调用MYSQL存储过程实例
  9. 引入OO开发报表后的感想
  10. Sql Server导出表结构Excel
  11. python大文件迭代器的流式读取,之前一直使用readlines()对于大文件可以迅速充满内存,之前用法太野蛮暴力,要使用xreadlines或是直接是f,
  12. c++ 指针、引用和取值;
  13. 算法 kmp算法
  14. Django的请求生命周期
  15. The thumbprint of same asymmetric key is not same in &#39;SQL Server Connector for Microsoft Azure Key Vault&#39; 1.0.4.0 and &#39;SQL Server Connector for Microsoft Azure Key
  16. 原生Ajax和jqueryAjax写法
  17. PHP最近做了物流快递查询的接口用得是快递100
  18. 使用Fiddler发送POST请求
  19. datatime模块
  20. Grid控件

热门文章

  1. 【整理】uclibc,eglibc,glibc之间的区别和联系
  2. java复习volatile关键字解析
  3. spring-boot-starter-actuator(健康监控)配置和使用
  4. memory management in oracle 11G R2
  5. 一个性能较好的jvm參数配置以及jvm的简单介绍
  6. JavaSE学习笔记--Item1 注解Annotation
  7. 到底什么是RPC?
  8. MySQL中採用类型varchar(20)和varchar(255)对性能上的影响
  9. There was a conflict between
  10. .NET平台下Redis使用(三)【ServiceStack.Redis学习】