Python Scrapy 爬取煎蛋网妹子图实例(一)
前面介绍了爬虫框架的一个实例,那个比较简单,这里在介绍一个实例
爬取 煎蛋网 妹子图,遗憾的是 上周煎蛋网还有妹子图了,但是这周妹子图变成了 随手拍,
不过没关系,我们爬图的目的是为了加强实战应用,管他什么图了先爬下来再说。
言归正传
这个实例,主要是讲将图片爬了下来,保存到本地,这个在上周已经实现了,这周有进一步做了讲图片信息保存到了数据库中。
代码结构

如上图
common 用来存放共代码,如上篇对数据库的操作进行了封装,这里直接就放到了common 文件夹下,方便调用。
紧接着下面两个文件夹是用来 存放爬取的图片的,第一个是 这周爬的 随手拍的图片,第二个是 妹子图的图片。
然后下面就是 爬虫文件了。
一下贴出 对应文件的代码
JdwSpider.py
# -*- coding: utf-8 -*-
import base64 import scrapy import JianDanW.items as items
from bs4 import BeautifulSoup class JdwspiderSpider(scrapy.Spider):
name = 'JdwSpider'
allowed_domains = ['jandan.net']
start_urls = ['http://jandan.net/ooxx/'] # start_urls = ['http://jandan.net/ooxx/page-1#comments'] def parse(self, response): item = items.JiandanwItem() # 通过 response.text 获取 html 源文件
html = response.text # 使用 lxml 解析器解析 html 此时 soup 为 html 样式文件。
soup = BeautifulSoup(html, 'lxml')
# 查找 html 中的 img-hash 返回 包含 class="img-hash" 的 列表
tags = soup.select('.img-hash')
imgUrlList = []
for tag in tags:
# tag 为 <span class="img-hash">Ly93eDQuc2luYWltZy5jbi9tdzYwMC82NmIzZGUxN2d5MWZ4bzZqaXM0aWVqMjFtYTB1MHg2ci5qcGc=</span>
# img_hash = Ly93eDQuc2luYWltZy5jbi9tdzYwMC82NmIzZGUxN2d5MWZ4bzZqaXM0aWVqMjFtYTB1MHg2ci5qcGc=
img_hash = tag.text
# img_hash 进行解密 为 //wx4.sinaimg.cn/mw600/66b3de17gy1fxo6jis4iej21ma0u0x6r.jpg
img_url = base64.b64decode(img_hash).decode('utf-8')
# 将结果加载到列表
imgUrlList.append(img_url) # print(img_urls)
# 将列表复制给item 对应的 image_urls
item['image_urls'] = imgUrlList yield item # 获取翻页 下一页 连接
p_url = response.xpath('//a[@class="previous-comment-page"]//@href').extract_first()
# 如果存在下一页
if p_url: p_url = str(p_url)
hurl = 'http:'
page_url = hurl + p_url
# 如果存在下一页,回调 parse 函数
yield scrapy.Request(page_url,callback=self.parse)
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 JiandanwItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
image_urls = scrapy.Field()#图片的链接
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 urllib import common.DBHandle as DBHandle class JiandanwPipeline(object):
def process_item(self, item, spider): # 数据库连接
host = '127.0.0.1'
username = 'adil'
password = 'helloyyj'
database = 'AdilTest'
port = 3306
DbHandle = DBHandle.DataBaseHandle(host, username, password, database, port)
for image_url in item['image_urls']:
# 截图图片链接
list_name = image_url.split('/')
# 获取图片名称
file_name = list_name[len(list_name) - 1] # 图片名称
# 获取当前路径
currentPath = os.getcwd()
# 拼接图片存放路径
file_path = os.path.join(currentPath,spider.name)
# 如果图片路径不存在,创建该文件路径
if not os.path.exists(file_path):
os.makedirs(file_path)
# 补全图片路径
path_name = os.path.join(file_path,file_name)
# 获取有效的url 因为 image_url = //wx4.sinaimg.cn/mw600/66b3de17gy1fxo6jis4iej21ma0u0x6r.jpg
image_url = 'http:' + image_url
# 此处执行 数据库插入,将 图片名称、url 插入到数据库 注意 这里的 values('占位符 一定要用 引号引起来,要不然执行不成功,血的教训')
sql = "insert into JdwSpider(image_name,image_url) values ('%s','%s')" % (file_name,image_url)
# 如果不执行插入,可以注释改该行代码
DbHandle.insertDB(sql) # 图片保存
with open(path_name, 'wb') as file_writer:
conn = urllib.request.urlopen(image_url) # 下载图片
# 保存图片
file_writer.write(conn.read())
file_writer.close()
# 关闭数据库
DbHandle.closeDb()
return item
配置 setting.py
# -*- coding: utf-8 -*- # Scrapy settings for JianDanW 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 = 'JianDanW' SPIDER_MODULES = ['JianDanW.spiders']
NEWSPIDER_MODULE = 'JianDanW.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'JianDanW (+http://www.yourdomain.com)' # Obey robots.txt rules
ROBOTSTXT_OBEY = True # 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',
#} # Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'JianDanW.middlewares.JiandanwSpiderMiddleware': 543,
#} # Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'JianDanW.middlewares.JiandanwDownloaderMiddleware': 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 = {
'JianDanW.pipelines.JiandanwPipeline': 300,
} # 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'
贴上爬虫结果图吧
本地文件

数据库存储信息

这样,即是 后面本地文件丢失,或是图片入口关闭,也可以通过重新读取数据库信息,重新下载了。
遇到的问题
因为煎蛋网 使用了反爬虫策略,所以导致 常规的爬虫 失败
需要增加 url 解密操作,具体 爬虫代码里有介绍
关于数据库操作的封装请看上篇介绍。
如果还有什么问题,可以评论区内提问,或是QQ 联系。
如果觉得有用,欢迎打赏哦,哈哈哈~
Python Scrapy 爬取煎蛋网妹子图实例(一)的更多相关文章
- Python Scrapy 爬取煎蛋网妹子图实例(二)
上篇已经介绍了 图片的爬取,后来觉得不太好,每次爬取的图片 都在一个文件下,不方便区分,且数据库中没有爬取的时间标识,不方便后续查看 数据时何时爬取的,所以这里进行了局部修改 修改一:修改爬虫执行方式 ...
- python爬虫–爬取煎蛋网妹子图片
前几天刚学了python网络编程,书里没什么实践项目,只好到网上找点东西做. 一直对爬虫很好奇,所以不妨从爬虫先入手吧. Python版本:3.6 这是我看的教程:Python - Jack -Cui ...
- python爬虫爬取煎蛋网妹子图片
import urllib.request import os def url_open(url): req = urllib.request.Request(url) req.add_header( ...
- Python 爬虫 爬取 煎蛋网 图片
今天, 试着爬取了煎蛋网的图片. 用到的包: urllib.request os 分别使用几个函数,来控制下载的图片的页数,获取图片的网页,获取网页页数以及保存图片到本地.过程简单清晰明了 直接上源代 ...
- Python 爬取煎蛋网妹子图片
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-08-24 10:17:28 # @Author : EnderZhou (z ...
- selenium爬取煎蛋网
selenium爬取煎蛋网 直接上代码 from selenium import webdriver from selenium.webdriver.support.ui import WebDriv ...
- python3爬虫爬取煎蛋网妹纸图片(上篇)
其实之前实现过这个功能,是使用selenium模拟浏览器页面点击来完成的,但是效率实际上相对来说较低.本次以解密参数来完成爬取的过程. 首先打开煎蛋网http://jandan.net/ooxx,查看 ...
- scrapy从安装到爬取煎蛋网图片
下载地址:https://www.lfd.uci.edu/~gohlke/pythonlibs/pip install wheelpip install lxmlpip install pyopens ...
- 爬虫实例——爬取煎蛋网OOXX频道(反反爬虫——伪装成浏览器)
煎蛋网在反爬虫方面做了不少工作,无法通过正常的方式爬取,比如用下面这段代码爬取无法得到我们想要的源代码. import requests url = 'http://jandan.net/ooxx' ...
随机推荐
- 闭包引起的onclick不起作用
问题描述:在html页面绑定onclick="cli()" 方法,定义在$(function( function cli(){} ))不起作用 $(function(){ func ...
- 快速阅读《QT5.9 c++开发指南》1
简介:<QT5.9 c++开发指南>的作者是和i三位主要从事地球物理探测仪器设计.数据处理方法研究和软件开发等工作的博士们,这本书以QT Widget为主要内容,比较全面地教授了QT开发桌 ...
- C语言动态链表数据结构
链表的操作增删改查 typedef int DATA; struct SNode { DATA data; SNode* pNext; }; SNode* g_head=NULL;//全局变量 //从 ...
- gcc,make,cmake
1.gcc是GNU Compiler Collection(就是GNU编译器套件),也可以简单认为是编译器,它可以编译很多种编程语言(括C.C++.Objective-C.Fortran.Java等等 ...
- 赞 ( 84 ) 微信好友 新浪微博 QQ空间 180 SSD故事会(14):怕TLC因为你不了解!【转】
本文转载自:https://diy.pconline.com.cn/750/7501340.html [PConline 杂谈]从前,大家谈TLC色变:如今,TLC攻占SSD半壁江山.是的,这个世界就 ...
- repo总结【转】
本文转载自:https://blog.csdn.net/weixin_38599972/article/details/78982408 1. repo start ##创建并切换分支repo st ...
- CentOS 使用 Docker 安装 Sentry
官网介绍:Sentry是一个实时事件日志记录和汇集的日志平台,其专注于错误监控,以及提取一切事后处理所需的信息.他基于Django开发,目的在于帮助开发人员从散落在多个不同服务器上的日志文件里提取发掘 ...
- FJNU2018低程A 逃跑路线(Lucas + 中国剩余定理 + LGV定理)题解
题目描述 n个人在w*h的监狱里面想要逃跑,已知他们的同伙在坐标(bi,h)接应他们,他们现在被关在(ai,1)现在他们必须要到同伙那里才有逃出去的机会,这n个人又很蠢只会从(x,y)->(x+ ...
- c# Database类的使用
参考资料http://ansonlh.iteye.com/blog/1689009 搜索:c# DatabaseFactory类
- [jsp & thymeleaf] - jsp和thymeleaf的共存解析
做项目时因为有些老jsp还需要测试用到,所以之前的thymeleaf也需要保持,配置如下: https://github.com/deadzq/jsp-thymeleaf 等空余时间在做详解吧!