python scrapy baidu image【转】
原 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【转】的更多相关文章
- python scrapy版 极客学院爬虫V2
python scrapy版 极客学院爬虫V2 1 基本技术 使用scrapy 2 这个爬虫的难点是 Request中的headers和cookies 尝试过好多次才成功(模拟登录),否则只能抓免费课 ...
- python Scrapy安装和介绍
python Scrapy安装和介绍 Windows7下安装1.执行easy_install Scrapy Centos6.5下安装 1.库文件安装yum install libxslt-devel ...
- Python.Scrapy.14-scrapy-source-code-analysis-part-4
Scrapy 源代码分析系列-4 scrapy.commands 子包 子包scrapy.commands定义了在命令scrapy中使用的子命令(subcommand): bench, check, ...
- Python.Scrapy.11-scrapy-source-code-analysis-part-1
Scrapy 源代码分析系列-1 spider, spidermanager, crawler, cmdline, command 分析的源代码版本是0.24.6, url: https://gith ...
- python scrapy cannot import name xmlrpc_client的解决方案,解决办法
安装scrapy的时候遇到如下错误的解决办法: "python scrapy cannot import name xmlrpc_client" 先执行 sudo pip unin ...
- 教程+资源,python scrapy实战爬取知乎最性感妹子的爆照合集(12G)!
一.出发点: 之前在知乎看到一位大牛(二胖)写的一篇文章:python爬取知乎最受欢迎的妹子(大概题目是这个,具体记不清了),但是这位二胖哥没有给出源码,而我也没用过python,正好顺便学一学,所以 ...
- 天气提醒邮件服务器(python + scrapy + yagmail)
天气提醒邮件服务器(python + scrapy + yagmail) 项目地址: https://gitee.com/jerry323/weatherReporter 前段时间因为xxx上班有时候 ...
- Python -- Scrapy 框架简单介绍(Scrapy 安装及项目创建)
Python -- Scrapy 框架简单介绍 最近在学习python 爬虫,先后了解学习urllib.urllib2.requests等,后来发现爬虫也有很多框架,而推荐学习最多就是Scrapy框架 ...
- python scrapy,beautifulsoup,regex,sgmparser,request,connection
In [2]: import requests In [3]: s = requests.Session() In [4]: s.headers 如果你是爬虫相关的业务?抓取的网站还各种各样, ...
随机推荐
- HTML5+CSS3 loading 效果收集--转载
用gif图片来做loading的时代已经过去了,它显得太low了,而用HTML5/CSS3以及SVG和canvas来做加载动画显得既炫酷又逼格十足.这已经成为一种趋势. 这里收集了几十个用html5和 ...
- linux/nginx命令
1.ps查看服务器所有的进程: -aux 显示所有状态 -ef 简洁信息 ps -aux | grep node 第二列是pid,杀掉程序使用kill. ps -ef | grep node 第一列是 ...
- mybatis08--关联查询多对一
根据省会的id查询出省会和对应国家的信息 01.多表的连接查询 修改对应的实体类信息 /** *国家的实体类 */ public class Country { private Integer cId ...
- Integer 的 valueOf 方法 与 常量池(对 String Pool 的部分理解)
举例: public class Test { @org.junit.Test public void intTest() { Integer t1 = 128; Integer t2 = 127; ...
- 二、JavaScript基础(2)
BOM基础加强 1.浏览器对象BOM DOM Window DOM Navigator DOM Screen DOM History DOM Location 2.浏览器对象的使用 History H ...
- partial_sum
版本1: template < class InputIterator, class OutputIterator > OutputIterator partial_sum(InputIt ...
- Linux wildcard
Linux中的通配符: 需要注意的是正则表达式与通配符完全是两个东西.wildcard代表的是bash操作接口的一个功能,而正则表达式是一种字符串处理的方法. 例如,'?',在通配符中表示一个字符,在 ...
- 实际体验Span<T> 的惊人表现
前言 最近做了一个过滤代码块功能的接口.就是获取一些博客文章做文本处理,然后这些博客文章的代码块太多了,很多重复的代码关键词如果被拿过来处理,那么会对文本的特征表示已经特征选择会有很大的影响.所以需要 ...
- 2018-2019-2 网络对抗技术 20165318 Exp2 后门原理与实践
2018-2019-2 网络对抗技术 20165318 Exp2 后门原理与实践 后门的基本概念及基础问题回答 常用后门工具 netcat Win获得Linux Shell Linux获得Win Sh ...
- apache tomcat (catalina)查版本(solaris/unix)
先进到tomcat的bin目录下(cd /tomcat目录/bin),在执行./version.sh https://blog.csdn.net/vv___/article/details/78653 ...