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 如果你是爬虫相关的业务?抓取的网站还各种各样, ...
随机推荐
- 命令行部署SharePoint2016离线前提条件和添加服务器的Feature
前言 Sp2016的软件环境要求如下: 服务器场中的数据库服务器的最低要求: 以下各项之一: Microsoft SQL Server 2014 Service Pack 1 (SP1) 的 64 位 ...
- win10 安装mysql
现在mysql压缩包:https://downloads.mysql.com/archives/community/ 在目录下新建data文件夹,my.ini文件,内容如下: [mysqld] bas ...
- ajax-addclass
- mybatis08--关联查询多对一
根据省会的id查询出省会和对应国家的信息 01.多表的连接查询 修改对应的实体类信息 /** *国家的实体类 */ public class Country { private Integer cId ...
- String字面量
public class assa{ static String ee = "aa";//ee指向常量池中的aa static String ff = new String(&qu ...
- MySql的主从复制以及读写分离详解
MySQL主从复制(Master-Slave)与读写分离(MySQL-Proxy)实践 Mysql作为目前世界上使用最广泛的免费数据库,相信所有从事系统运维的工程师都一定接触过.但在实际的生产环境中, ...
- Gym 101981J - Prime Game - [数学题][线性筛+分解质因数][2018-2019 ACM-ICPC Asia Nanjing Regional Contest Problem J]
题目链接:http://codeforces.com/gym/101981/attachments 题意: 令 $mul(l,r) = \prod_{i=l}^{r}a_i$,且 $fac(l,r)$ ...
- 分析Hello2代码
代码如下String username = request.getParameter("username"); if (username != null && us ...
- 判断是手机请求还是pc请求
网址 http://detectmobilebrowsers.com/ string u = Request.ServerVariables["HTTP_USER_AGENT"]; ...
- Oracle 数据库逻辑结构2.md
Oracle 数据库逻辑结构一.存储关系Oracle 数据库逻辑上是由一个或多个表空间组成的,表空间物理上是由一个或多个数据文件组成的:而在逻辑上表空间又是由一个或多个段组成的.在Oracle 数据库 ...