第一次写博客 有什么需要改进的地方欢迎留言改进
本次代码运行是基于Linux系统 python3 scrapy框架运行
1.先看结果
2.接着上代码
spider
# -*- coding: utf-8 -*-
import scrapy
class Tu699Spider(scrapy.Spider):
name = 'tu_699'
allowed_domains = ['699pic.com']
start_urls = ['http://699pic.com/people.html']
def parse(self, response):
li_list = response.xpath("//div[@class='swipeboxEx']/div")
item = {}
for li in li_list:
# 获取图片url
item["img_url"] = li.xpath("./a/img/@data-original").extract_first()
# 获取图片名称
item["img_name"] = li.xpath("./a/img/@title").extract_first()
yield item
# 获取下一页
url = response.xpath("//a[@class='downPage']/@href").extract_first()
# 判断是否为空
if url is not None:
# 下一页拼接
next_url = "http://699pic.com/" + url
# 发送下一页请求
yield scrapy.Request(next_url, callback=self.parse)
pipelines
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import re
import requests
class XiaohuarPipeline(object):
def process_item(self, item, spider):
# 对图片的名称进行简单的处理
item["img_name"] = re.sub(r"图片下载", "", item["img_name"])
# 发送图片链接请求
item["img"] = requests.get(item["img_url"])
# 保存
name = "tu_699/" + item["img_name"] + ".jpg"
with open(name, 'wb') as f:
f.write(item["img"].content)
return item
settings
网站没有什么反扒措施
把ROBOTSTXT_OBEY该为False就好了
3.最后说明
刚学爬虫没多久 第一次尝试爬取图片 网上看其他人写的感觉有点复杂 直接自己安装思路写了个 路子有点野 还好完成了 有什么问题欢迎留言指出 共同进步(第一次写博客 比较渣
)