原 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. shell脚本监控网站状态

    shell脚本监控网站状态 #!/bin/sh date=`date +"%Y%m%d-%H%M"` title="status" contentFail=&q ...

  2. Nodejs exec和spawn的区别

    spawn child_process.spaen会返回一个带有stdout和stderr流的对象.你可以通过stdout流来读取子进程返回给Node.js的数据. stdout拥有’data’,’e ...

  3. gitlab的fork及源项目的同步

    此篇大部分貌似是cp其他地方的,也忘了出处,写到此处,权当保存,见谅. 测试代码master同步到生产代码master   #现有git@gitlab.home.com:root/fork.git项目 ...

  4. 从零开始搭建Go语言开发环境

    一步一步,从零搭建Go语言开发环境. 安装Go语言及搭建Go语言开发环境 下载 下载地址 Go官网下载地址:https://golang.org/dl/ Go官方镜像站(推荐):https://gol ...

  5. Java课程寒假之《人月神话》有感之一

    一.焦油坑 以前上课的时候,老师讲过早期的程序由于工作量不大,大多只需要几个人完成,随着软件规模的不断扩大,代码量直线上升,仅仅一两个人可能没有办法完成这样的任务,多以开始形成了团队的规模,焦油坑说的 ...

  6. 关于 telegram中 callback_data <= 64bytes 的解决方法

    解决方法: # bind data to uuid import uuid my_data = long_json_string my_uuid = uuid.uuid4() user_data[my ...

  7. Oracle课程档案,第三天

    count(*):有多少行,对行做统计 count(x):列.... sum:和 avg:平均值 min:求最小值 max:求最大值 distinct:取出重复的值 count:计数 group by ...

  8. python--列表,元组,字符串互相转换

    列表,元组和字符串python中有三个内建函数:,他们之间的互相转换使用三个函数,str(),tuple()和list(),具体示例如下所示 >>> s = "xxxxx& ...

  9. Codeforces 1089E - Easy Chess - [DFS+特判][2018-2019 ICPC, NEERC, Northern Eurasia Finals Problem E]

    题目链接:https://codeforces.com/contest/1089/problem/E Elma is learning chess figures. She learned that ...

  10. 初始Redis

    一.NoSql数据库(Not Only Sql): 1.又称为非关系型数据库,主流的NoSql数据库有: Redis,Hbase,MongoDB 2.NoSql产生的背景: 1.1.数据库的高并发的读 ...