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 如果你是爬虫相关的业务?抓取的网站还各种各样, ...
随机推荐
- 解决Office 2016客户端如何同SharePoint Server2016安装在一起
前言 Microsoft Office 2016 客户端默认使用新式验证. 在某些配置中,新式验证不受安装有 SharePoint Server 2016 的 Office 2016 客户端的支持,例 ...
- mssql for xml path使用
准备工作: CREATE TABLE [dbo].[Students]( [id] [int] IDENTITY(1,1) NOT NULL, [names] [varchar](50) NULL, ...
- 下载Crypto,CyCrypto,PyCryptodome 报错问题
python下载Crypto,CyCrypto,PyCryptodome,如有site-packages中存在crypto.pycrypto,在pip之前,需要pip3 uninstall crypt ...
- 使用call、apply和bind解决js中烦人的this,事件绑定时的this和传参问题
1.什么是this 在JavaScript中this可以是全局对象.当前对象或者任意对象,这完全取决于函数的调用方式,this 绑定的对象即函数执行的上下文环境(context). 为了帮助理解,让我 ...
- HTML5语音合成Speech Synthesis API简介
by zhangxinxu from http://www.zhangxinxu.com/wordpress/?p=5865本文可全文转载,但需得到原作者书面许可,同时保留原作者和出处,摘要引流则随意 ...
- 用SQL快速删除U8账套
一.问题提出 通过"系统管理"来删除999账套,首先要求你备份然后才能删除.头痛的是: 1)备份需要发费很长的时间,特别是账套数据文件比较大时. 2)备份时,你的本本基本处于死机状 ...
- javascript 窗口宽高滚动
//不加window IE不支持 console.info(window.screenLeft);//IE支持火狐不支持 console.info(window.screenX);//火狐支持,IE不 ...
- laravel队列使用
1.修改.env中queue_driver = databases 2.php artisan queue:table 在database 目录下migrations里面有对应的表 3.执行迁移文件 ...
- 【转载】MDK环境下让STM32用上FreeRTOS v8.1.2和FreeRTOS+Trace v2.6.0全过程
[转载]https://www.amobbs.com/thread-5601460-1-2.html?_dsign=6a59067b 本人选择使用FreeRTOS的最大原因就是想使用FreeRTO ...
- spring相关jar包
spring.jar是包含有完整发布的单个jar 包,spring.jar中包含除了spring-mock.jar里所包含的内容外其它所有jar包的内容,因为只有在开发环境下才会用到 spring-m ...