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 ZipFile模块详解
Nov 01 Python
python正则匹配查询港澳通行证办理进度示例分享
Dec 27 Python
深入理解Python对Json的解析
Feb 14 Python
python bottle框架支持jquery ajax的RESTful风格的PUT和DELETE方法
May 24 Python
python 脚本生成随机 字母 + 数字密码功能
May 26 Python
Python 带有参数的装饰器实例代码详解
Dec 06 Python
Pandas读取并修改excel的示例代码
Feb 17 Python
Python3使用Matplotlib 绘制精美的数学函数图形
Apr 11 Python
Django使用模板后无法找到静态资源文件问题解决
Jul 19 Python
Python标准库json模块和pickle模块使用详解
Mar 10 Python
详解torch.Tensor的4种乘法
Sep 03 Python
Python爬虫进阶之爬取某视频并下载的实现
Dec 08 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语法(3)
2006/10/09 PHP
php获得文件大小和文件创建时间的方法
2015/03/13 PHP
php防止网站被攻击的应急代码
2015/10/21 PHP
php使用curl并发减少后端访问时间的方法分析
2016/05/12 PHP
jquery+thinkphp实现跨域抓取数据的方法
2016/10/15 PHP
jquery中dom操作和事件的实例学习-表单验证
2011/11/30 Javascript
jquery及原生js获取select下拉框选中的值示例
2013/10/25 Javascript
浅析jquery某一元素重复绑定的问题
2014/01/03 Javascript
javascript显示上周、上个月日期的处理方法
2016/02/03 Javascript
JS使用正则表达式实现关键字替换加粗功能示例
2016/08/03 Javascript
bootstrapValidator 重新启用提交按钮的方法
2017/02/20 Javascript
JS判断数组那点事
2017/10/10 Javascript
详解如何使用babel进行es6文件的编译
2018/05/29 Javascript
在Vue methods中调用filters里的过滤器实例
2018/08/30 Javascript
Node.js使用supervisor进行开发中调试的方法
2019/03/26 Javascript
使用Vue开发自己的Chrome扩展程序过程详解
2019/06/21 Javascript
微信小程序 网络通信实现详解
2019/07/23 Javascript
浅谈python中的变量默认是什么类型
2016/09/11 Python
Python中的集合介绍
2019/01/28 Python
python程序快速缩进多行代码方法总结
2019/06/23 Python
Python使用itchat 功能分析微信好友性别和位置
2019/08/05 Python
Python如何绘制日历图和热力图
2020/08/07 Python
python七种方法判断字符串是否包含子串
2020/08/18 Python
Python xlrd/xlwt 创建excel文件及常用操作
2020/09/24 Python
深入浅析css3 中display box使用方法
2015/11/25 HTML / CSS
Clearly新西兰:购买眼镜、太阳镜和隐形眼镜
2018/04/26 全球购物
ALDO加拿大官网:加拿大女鞋品牌
2018/12/22 全球购物
Araks官网:纽约内衣品牌
2020/10/15 全球购物
上班睡觉检讨书
2014/01/09 职场文书
致铅球运动员广播稿精选
2014/01/12 职场文书
水利学院求职自荐书
2014/02/01 职场文书
《青山处处埋忠骨》教学反思
2014/04/22 职场文书
王亚平太空授课观后感
2015/06/12 职场文书
python3 实现mysql数据库连接池的示例代码
2021/04/17 Python
python图像处理基本操作总结(PIL库、Matplotlib及Numpy)
2021/06/08 Python
微信小程序 WeUI扩展组件库的入门教程
2022/04/21 Javascript