原 https://github.com/vivianLL/baidupictures

#!/usr/bin/env Python
# coding=utf-8
#__author__ = 'leilu' import json
import itertools
import urllib
import requests
import os
import re
import codecs
import sys
import imghdr reload(sys)
sys.setdefaultencoding("utf-8") str_table = {
'_z2C$q': ':',
'_z&e3B': '.',
'AzdH3F': '/'
} char_table = {
'w': 'a',
'k': 'b',
'v': 'c',
'': 'd',
'j': 'e',
'u': 'f',
'': 'g',
'i': 'h',
't': 'i',
'': 'j',
'h': 'k',
's': 'l',
'': 'm',
'g': 'n',
'': 'o',
'r': 'p',
'q': 'q',
'': 'r',
'f': 's',
'p': 't',
'': 'u',
'e': 'v',
'o': 'w',
'': '',
'd': '',
'n': '',
'': '',
'c': '',
'm': '',
'': '',
'b': '',
'l': '',
'a': ''
} # str 的translate方法需要用单个字符的十进制unicode编码作为key
# value 中的数字会被当成十进制unicode编码转换成字符
# 也可以直接用字符串作为value
char_table = {ord(key): ord(value) for key, value in char_table.items()} # 解码图片URL
def decode(url):
# 先替换字符串
for key, value in str_table.items():
url = url.replace(key, value)
# 再替换剩下的字符
return url.translate(char_table) # 生成网址列表
def buildUrls(word):
word = urllib.quote(word)
url = r"http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&fp=result&queryWord={word}&cl=2&lm=-1&ie=utf-8&oe=utf-8&st=-1&ic=0&word={word}&face=0&istype=2nc=1&pn={pn}&rn=60"
urls = (url.format(word=word, pn=x) for x in itertools.count(start=0, step=60))
return urls # 解析JSON获取图片URL
re_url = re.compile(r'"objURL":"(.*?)"')
def resolveImgUrl(html):
imgUrls = [decode(x) for x in re_url.findall(html)]
return imgUrls def downImg(imgUrl, dirpath, imgName):
tempfile = os.path.join(dirpath, imgName)
try:
res = requests.get(imgUrl, timeout=15)
if str(res.status_code)[0] == "":
print(str(res.status_code), ":" , imgUrl)
return False
except Exception as e:
print("抛出异常:", imgUrl)
print(e)
return False
with open(tempfile, "wb") as f:
f.write(res.content)
if os.path.getsize(tempfile) < 1024*10:
print("small file")
return False
if imghdr.what(tempfile) == 'png':
filename = os.path.join(dirpath, imgName+'.png')
elif imghdr.what(tempfile) =='jpeg':
filename = os.path.join(dirpath, imgName+'.jpg')
elif imghdr.what(tempfile) =='jpg':
filename = os.path.join(dirpath, imgName+'.jpg')
elif imghdr.what(tempfile) =='bmp':
filename = os.path.join(dirpath, imgName+'.bmp')
else:
print(imghdr.what(tempfile))
return False
os.remove(tempfile)
with open(filename, "wb") as f:
f.write(res.content)
return True def mkdir(path):
path = path.strip()
dirpath = os.path.join("/home/aimhabo/getBaiduiImage/images/",path)
if not os.path.exists(dirpath):
print ("新建文件夹")
os.makedirs(dirpath)
print (dirpath)
return dirpath if __name__ == '__main__':
#f = open('/home/aimhabo/getBaiduiImage/images.txt', 'r')
#for line in f:
# word = line.strip().decode('utf-8')
word = 'cats猫'
print("正在搜索:", word)
dirpath = mkdir(word) word = str(word)
urls = buildUrls(word)
index = 1000
index_max = 1050
for url in urls:
print("正在请求:", url)
html = requests.get(url, timeout=10).content.decode('utf-8')
imgUrls = resolveImgUrl(html)
if len(imgUrls) == 0: # 没有图片则结束
break
for url in imgUrls:
if downImg(url, dirpath, str(index)):
index += 1
print("index now on %s" % index)
if index > index_max:
break
if index > index_max:
break #f.close()

python scrapy baidu image【转】的更多相关文章

  1. python scrapy版 极客学院爬虫V2

    python scrapy版 极客学院爬虫V2 1 基本技术 使用scrapy 2 这个爬虫的难点是 Request中的headers和cookies 尝试过好多次才成功(模拟登录),否则只能抓免费课 ...

  2. python Scrapy安装和介绍

    python Scrapy安装和介绍 Windows7下安装1.执行easy_install Scrapy Centos6.5下安装 1.库文件安装yum install libxslt-devel ...

  3. Python.Scrapy.14-scrapy-source-code-analysis-part-4

    Scrapy 源代码分析系列-4 scrapy.commands 子包 子包scrapy.commands定义了在命令scrapy中使用的子命令(subcommand): bench, check, ...

  4. Python.Scrapy.11-scrapy-source-code-analysis-part-1

    Scrapy 源代码分析系列-1 spider, spidermanager, crawler, cmdline, command 分析的源代码版本是0.24.6, url: https://gith ...

  5. python scrapy cannot import name xmlrpc_client的解决方案,解决办法

    安装scrapy的时候遇到如下错误的解决办法: "python scrapy cannot import name xmlrpc_client" 先执行 sudo pip unin ...

  6. 教程+资源,python scrapy实战爬取知乎最性感妹子的爆照合集(12G)!

    一.出发点: 之前在知乎看到一位大牛(二胖)写的一篇文章:python爬取知乎最受欢迎的妹子(大概题目是这个,具体记不清了),但是这位二胖哥没有给出源码,而我也没用过python,正好顺便学一学,所以 ...

  7. 天气提醒邮件服务器(python + scrapy + yagmail)

    天气提醒邮件服务器(python + scrapy + yagmail) 项目地址: https://gitee.com/jerry323/weatherReporter 前段时间因为xxx上班有时候 ...

  8. Python -- Scrapy 框架简单介绍(Scrapy 安装及项目创建)

    Python -- Scrapy 框架简单介绍 最近在学习python 爬虫,先后了解学习urllib.urllib2.requests等,后来发现爬虫也有很多框架,而推荐学习最多就是Scrapy框架 ...

  9. python scrapy,beautifulsoup,regex,sgmparser,request,connection

    In [2]: import requests   In [3]: s = requests.Session()   In [4]: s.headers 如果你是爬虫相关的业务?抓取的网站还各种各样, ...

随机推荐

  1. [转]MapReduce:详解Shuffle过程

    Shuffle过程是MapReduce的核心,也被称为奇迹发生的地方.要想理解MapReduce, Shuffle是必须要了解的.我看过很多相关的资料,但每次看完都云里雾里的绕着,很难理清大致的逻辑, ...

  2. docker学习(一)

    在工作和生活中免不了要学习新的东西.学习新东西要和已有的东西相结合,要有较快的效率.今天学习一下docker的使用,也锻炼一下自己学习新东西的能力. 1.学习docker,首先要下载docker.首先 ...

  3. 解决键盘输入被JDB占用的问题

    解决键盘输入被JDB占用的问题 本周的任务"迭代和JDB"在使用JDB调试时需要键盘输入数据,但我在正确的位置输入数据后发现JDB提示如图所示的错误. 上网查找后得知该错误的产生是 ...

  4. Ubuntu 使用命令行连接无线网

    一.查看可以使用的无线网: nmcli dev wifi 二.连接无线网: nmcli dev wifi connect ‘essid’(网络名称) password ‘password’(密码) 可 ...

  5. 谈谈那些年我们装B的并发编程

    谈谈那些年我们装B的并发编程 每个人对并发编程的理解会有差异,但是终极目标始终是追求尽可能高的处理性能.那么如何尽可能的提升处理性能呢? 我们可以从单核,多核,并发,并行的基础出发.首先,介绍下基础知 ...

  6. python 模块大全

    logging   time datetime   sys   os   json  random   hashlib   paramiko  pymysql模块使用 subprocess  pywi ...

  7. C#基础加强(8)之委托和事件

    委托 简介 委托是一种可以声明出指向方法的变量的数据类型. 声明委托的方式 格式: delegate <返回值类型> 委托类型名(参数) ,例如: delegate void MyDel( ...

  8. oracle 新建用户后赋予的权限语句

    grant create session,resource to itsys; grant create table to itsys;grant resource to itsys;grant cr ...

  9. Python基础学习之Python主要的数据分析工具总结

    Python主要是依靠众多的第三方库来增强它的数据处理能力的.常用的是Numpy库,Scipy库.Matplotlib库.Pandas库.Scikit-Learn库等. 常规版本的python需要在安 ...

  10. python列表常用内建方法

    python列表常用内建方法: abc = ['a',1,3,'a'] #abc.pop(1) #删除索引1的值.结果['a', 3] #abc.append([123]) #结果:['a', 1, ...