CSS 反爬之字体反爬
郑重声明:本项目的所有代码和相关文章, 仅用于经验技术交流分享,禁止将相关技术应用到不正当途径,因为滥用技术产生的风险与本人无关。
字体反爬原理
- 字体反爬也就是自定义字体反爬,通过调用自定义的ttf或woff等文件来渲染网页中的文字,而网页中的文字不再是文字,而是相应的字体编码,通过复制或者简单的采集是无法采集到编码后的文字内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
@font-face {
/*自定义字体样式名称*/
font-family: "mtsi-font";
/*引入字体文件*/
src: url("aHR0cHM6Ly9zM3BsdXMubWVpdHVhbi5uZXQvdjEvbXNzXzczYTUxMWI4ZjkxZjQzZDBiZGFlOTI1ODRlYTYzMzBiL2ZvbnQvMDYwYmU5MzAud29mZg==");
}
.stonefont {
/*引用自定义字体*/
font-family: mtsi-font;
}
</style>
</head>
<body>
<!--通过十六进制编码来映射字体 爬虫只能爬取到字符编码,网页却能正常显示-->
<p class="stonefont">.</p>
</body>
</html>
破解字体加密
pip install Pillow ddddocr TTFont
- 适用于任何字体反爬
from PIL import ImageFont, Image, ImageDraw
from io import BytesIO
import ddddocr
from fontTools.ttLib import TTFont
def font_to_img(txt, filename):
'''将字体画成图片'''
img_size = 1024
img = Image.new('1', (img_size, img_size), 255)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(filename, int(img_size * 0.7))
txt = chr(txt)
x, y = draw.textsize(txt, font=font)
draw.text(
((img_size - x) // 2, (img_size - y) // 2),
txt, font=font,
fill=0
)
return img
def font_analysis(filename):
'''传入字体文件名称返回字体映射表'''
result = {}
font = TTFont(filename)
ocr = ddddocr.DdddOcr(show_ad=False)
for i, Glyphname in font.getBestCmap().items():
pil = font_to_img(i, filename)
bytes_io = BytesIO()
pil.save(bytes_io, format="PNG")
res = ocr.classification(bytes_io.getvalue())
result[Glyphname] = res
return result
if __name__ == '__main__':
r = font_analysis('maoyan_score.woff')
print(r)