python脚本爬取字体文件的实现方法


Posted in Python onApril 29, 2017

前言

大家应该都有所体会,为了提高验证码的识别准确率,我们当然要首先得到足够多的测试数据。验证码下载下来容易,但是需要人脑手工识别着实让人受不了,于是我就想了个折衷的办法——自己造验证码。

为了保证多样性,首先当然需要不同的字模了,直接用类似ttf格式的字体文件即可,网上有很多ttf格式的字体包供我们下载。当然,我不会傻到手动下载解压缩,果断要写个爬虫了。

实现方法

网站一:fontsquirrel.com

这个网站的字体可以免费下载,但是有很多下载点都是外链连接到其他网站的,这部分得忽略掉。

#coding:utf-8
import urllib2,cookielib,sys,re,os,zipfile
import numpy as np
#网站登陆
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders=[('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36))')]
urllib2.install_opener(opener)
#搜索可下载连接
def search(path):
 request=urllib2.Request(path)
 response=urllib2.urlopen(request)
 html=response.read()
 html=html.replace('\n',' ')#将所有的回车去掉,因为正则表达式是单行匹配。。。。。。
 urls=re.findall(r'<a href="(.*?)" rel="external nofollow" >(.*?)</a>',html)
 for i in urls:
  url,inner=i
  if not re.findall(r'Download ',inner)==[] and re.findall(r'offsite',inner)==[] and url not in items:
   items.append(url)
items=[]#保存下载地址
for i in xrange(15):
 host='http://www.fontsquirrel.com/fonts/list/find_fonts/'+str(i*50)+'?filter%5Bdownload%5D=local'
 search(host)
if not os.path.exists('ttf'):
 os.mkdir('ttf')
os.chdir('ttf')
def unzip(rawfile,outputdir):
 if zipfile.is_zipfile(rawfile):
  print 'yes'
  fz=zipfile.ZipFile(rawfile,'r')
  for files in fz.namelist():
   print(files) #打印zip归档中目录
   fz.extract(files,outputdir)#解压缩文件
 else:
  print 'no'
for i in items: 
 print i
 request=urllib2.Request('http://www.fontsquirrel.com'+i)
 response=urllib2.urlopen(request)
 html=response.read()
 name=i.split('/')[-1]+'.zip'
 f=open(name,'w')
 f.write(html)
 f.close()#文件记得关闭,否则下面unzip会出错
 unzip(name,'./')
 os.remove(name)
os.listdir(os.getcwd())
os.chdir('../')
files=os.listdir('ttf/')
for i in files:#删除无用文件
 if not (i.split('.')[-1]=='ttf' or i.split('.')[-1]=='otf'):
  if os.path.isdir(i):
   os.removedirs('ttf/'+i)
  else:
   os.remove('ttf/'+i)
print len(os.listdir('ttf/'))

搞到了2000+个字体,种类也挺多的,蛮好。

网站二:dafont.com

这个网站的字体花样比较多,下载起来也比较方便,恶心的是他的文件名的编码好像有点问题。

#coding:utf-8
import urllib2,cookielib,sys,re,os,zipfile
import shutil
import numpy as np
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders=[('User-agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36))')]
urllib2.install_opener(opener)
items=[]
def search(path):
 request=urllib2.Request(path)
 response=urllib2.urlopen(request)
 html=response.read()
 html=html.replace('\n',' ')
 urls=re.findall(r'href=\"(http://dl.dafont.com/dl/\?f=.*?)\" >',html)
 items.extend(urls)
for i in xrange(117):
 host='http://www.dafont.com/new.php?page='+str(i+1)
 search(host)
 print 'Page'+str(i+1)+'done'
 items=list(set(items))
 print len(items)
if not os.path.exists('ttf2'):
 os.mkdir('ttf2')
os.chdir('ttf2')
def unzip(rawfile,outputdir):
 if zipfile.is_zipfile(rawfile):
  print 'yes'
  fz=zipfile.ZipFile(rawfile,'r')
  for files in fz.namelist():
   print(files) #打印zip归档中目录
   fz.extract(files,outputdir)
 else:
  print 'no'
for i in items: 
 print i
 request=urllib2.Request(i)
 response=urllib2.urlopen(request)
 html=response.read()
 name=i.split('=')[-1]+'.zip'
 f=open(name,'w')
 f.write(html)
 f.close()
 unzip(name,'./')
 os.remove(name)
print os.listdir(os.getcwd())
for root ,dire,fis in os.walk('./'):#递归遍历文件夹
 for i in fis:
  if not (i.split('.')[-1]=='ttf' or i.split('.')[-1]=='otf'):
   os.remove(root+i)
   print i
for i in os.listdir('./'):
 if os.path.isdir(i):
  os.rmdir(i)
os.chdir('../')

总体操作跟之前的差不多,跑了几十分钟下了4000多的字体。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
使用python删除nginx缓存文件示例(python文件操作)
Mar 26 Python
解决python写的windows服务不能启动的问题
Apr 15 Python
Python基于dom操作xml数据的方法示例
May 12 Python
Python基于property实现类的特性操作示例
Jun 15 Python
详解python异步编程之asyncio(百万并发)
Jul 07 Python
Python最小二乘法矩阵
Jan 02 Python
python 用for循环实现1~n求和的实例
Feb 01 Python
详解Python函数式编程—高阶函数
Mar 29 Python
Django中使用极验Geetest滑动验证码过程解析
Jul 31 Python
Python 实用技巧之利用Shell通配符做字符串匹配
Aug 23 Python
Python接口自动化测试框架运行原理及流程
Nov 30 Python
python中的sys模块和os模块
Mar 20 Python
Python在图片中添加文字的两种方法
Apr 29 #Python
Python实现对字符串的加密解密方法示例
Apr 29 #Python
Python实现通过文件路径获取文件hash值的方法
Apr 29 #Python
python基于pyDes库实现des加密的方法
Apr 29 #Python
Python简单实现Base64编码和解码的方法
Apr 29 #Python
Python变量和字符串详解
Apr 29 #Python
python实现unicode转中文及转换默认编码的方法
Apr 29 #Python
You might like
PHP 字符截取 解决中文的截取问题,不用mb系列
2009/09/29 PHP
yii2 resetful 授权验证详解
2017/05/18 PHP
ext form 表单提交数据的方法小结
2008/08/08 Javascript
怎么清空javascript数组
2013/05/11 Javascript
谈谈对offsetleft兼容性的理解
2015/11/11 Javascript
Hammer.js+轮播原理实现简洁的滑屏功能
2016/02/02 Javascript
JQuery日期插件datepicker的使用方法
2016/03/03 Javascript
在Node.js中使用Javascript Generators详解
2016/05/05 Javascript
jquery实现焦点轮播效果
2017/02/23 Javascript
微信分享调用jssdk实例
2017/06/08 Javascript
JavaScript之事件委托实例(附原生js和jQuery代码)
2017/07/22 jQuery
简单实现jQuery弹窗效果
2017/10/30 jQuery
vue axios整合使用全攻略
2018/05/24 Javascript
vue配置font-awesome5的方法步骤
2019/01/27 Javascript
layui的layedit富文本赋值方法
2019/09/18 Javascript
react用Redux中央仓库实现一个todolist
2019/09/29 Javascript
VUE解决 v-html不能触发点击事件的问题
2019/10/28 Javascript
基础的十进制按位运算总结与在Python中的计算示例
2016/06/28 Python
Linux RedHat下安装Python2.7开发环境
2017/05/20 Python
Python读取properties配置文件操作示例
2018/03/29 Python
Python删除n行后的其他行方法
2019/01/28 Python
python lambda函数及三个常用的高阶函数
2020/02/05 Python
使用wxpy实现自动发送微信消息功能
2020/02/28 Python
纯CSS3实现运行时钟的示例代码
2021/01/25 HTML / CSS
什么时候需要进行强制类型转换
2016/09/03 面试题
员工薪酬激励方案
2014/06/13 职场文书
大专学生求职信
2014/07/04 职场文书
个人主要事迹材料
2014/08/26 职场文书
写给老师的感谢信
2015/01/20 职场文书
2017年大学生寒假社会实践活动总结
2016/04/06 职场文书
利用Python判断你的密码难度等级
2021/06/02 Python
浅谈Python响应式类库RxPy
2021/06/14 Python
python常见的占位符总结及用法
2021/07/02 Python
Python anaconda安装库命令详解
2021/10/16 Python
分享node.js实现简单登录注册的具体代码
2022/04/26 NodeJs
聊聊CSS粘性定位sticky案例解析
2022/06/01 HTML / CSS