在爬取网站抓取数据的过程中,有时会遇到这样一种情况:网页浏览正常,开发者模式(F12)查看原来没之后发现关键数据乱码,当然爬取下来的结果也是乱码。这种反爬策略一般称之为字体反爬。
以58同城为例:
用浏览器随便打开58同城的一个页面,F12调出开发者调试窗口:
网页显示正常,调试窗口出现的内容与页面显示不符。
回到网页上,右键查看网页源代码,搜索base64关键字,可以看到一大串用base64加密的字符,复制逗号之后单引号之前的字符串:
编写Python代码,用base64把复制下来的加密字符串进行解码并保存为58.ttf
:
import base64
font_face = "AAEAAAALAIAAAwAwR1NVQiCLJXoAAAE4AAAAVE9TLzL4XQjtAAABjAAAAFZjbWFwq8N/ZAAAAhAAAAIuZ2x5ZuWIN0cAAARYAAADdGhlYWQVET67AAAA4AAAADZoaGVhCtADIwAAALwAAAAkaG10eC7qAAAAAAHkAAAALGxvY2ED7gSyAAAEQAAAABhtYXhwARgANgAAARgAAAAgbmFtZTd6VP8AAAfMAAACanBvc3QFRAYqAAAKOAAAAEUAAQAABmb+ZgAABLEAAAAABGgAAQAAAAAAAAAAAAAAAAAAAAsAAQAAAAEAAOi9HBZfDzz1AAsIAAAAAADYxPnVAAAAANjE+dUAAP/mBGgGLgAAAAgAAgAAAAAAAAABAAAACwAqAAMAAAAAAAIAAAAKAAoAAAD/AAAAAAAAAAEAAAAKADAAPgACREZMVAAObGF0bgAaAAQAAAAAAAAAAQAAAAQAAAAAAAAAAQAAAAFsaWdhAAgAAAABAAAAAQAEAAQAAAABAAgAAQAGAAAAAQAAAAEERAGQAAUAAAUTBZkAAAEeBRMFmQAAA9cAZAIQAAACAAUDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBmRWQAQJR2n6UGZv5mALgGZgGaAAAAAQAAAAAAAAAAAAAEsQAABLEAAASxAAAEsQAABLEAAASxAAAEsQAABLEAAASxAAAEsQAAAAAABQAAAAMAAAAsAAAABAAAAaYAAQAAAAAAoAADAAEAAAAsAAMACgAAAaYABAB0AAAAFAAQAAMABJR2lY+ZPJpLnjq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ZXRWZXJzaW9uIDEuMGZhbmdjaGFuLXNlY3JldEdlbmVyYXRlZCBieSBzdmcydHRmIGZyb20gRm9udGVsbG8gcHJvamVjdC5odHRwOi8vZm9udGVsbG8uY29tAGYAYQBuAGcAYwBoAGEAbgAtAHMAZQBjAHIAZQB0AFIAZQBnAHUAbABhAHIAZgBhAG4AZwBjAGgAYQBuAC0AcwBlAGMAcgBlAHQAZgBhAG4AZwBjAGgAYQBuAC0AcwBlAGMAcgBlAHQAVgBlAHIAcwBpAG8AbgAgADEALgAwAGYAYQBuAGcAYwBoAGEAbgAtAHMAZQBjAHIAZQB0AEcAZQBuAGUAcgBhAHQAZQBkACAAYgB5ACAAcwB2AGcAMgB0AHQAZgAgAGYAcgBvAG0AIABGAG8AbgB0AGUAbABsAG8AIABwAHIAbwBqAGUAYwB0AC4AaAB0AHQAcAA6AC8ALwBmAG8AbgB0AGUAbABsAG8ALgBjAG8AbQAAAAIAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwECAQMBBAEFAQYBBwEIAQkBCgELAQwAAAAAAAAAAAAAAAAAAAAA"
b = base64.b64decode(font_face)
with open('58.ttf', 'wb') as f:
f.write(b)
用Python第三方库fontTools
来获取字体映射表。
安装fontTools
:
pip install fontTools
先来看下ttf文件中有哪些信息,直接打开ttf文件那当然看不了,把它转换成xml文件就可以查看了:
from fontTools.ttLib import TTFont
font = TTFont('58.ttf') # 打开刚才保存在本地的58.ttf文件
font.saveXML('58.xml') # 转换并保存为xml
打开58.xml文件,可以看到类似html标签的文件结构:
点开GlyphOrder标签,可以看到id和name:
点开cmap标签,是code和name的对应关系:
用代码来获取编码和name的对应关系:
from fontTools.ttLib import TTFont
font = TTFont('58.ttf') # 打开本地的ttf文件
bestcmap = font['cmap'].getBestCmap()
print(bestcmap)
输出如下:
{38006: 'glyph00007', 38287: 'glyph00005', 39228: 'glyph00009', 39499: 'glyph00004', 40506: 'glyph00008', 40611: 'glyph00003', 40804: 'glyph00006', 40850: 'glyph00002', 40868: 'glyph00001', 40869: 'glyph00010'}
输出的是一个字典,key是编码的int型(十进制)
我们把这个字典转一下,变成编码和正常字体的映射关系:
import re
from fontTools.ttLib import TTFont
font = TTFont('58.ttf') # 打开本地的ttf文件
bestcmap = font['cmap'].getBestCmap()
newmap = dict()
for key in bestcmap.keys():
value = int(re.search(r'(\d+)', bestcmap[key]).group(1)) - 1
key = hex(key)
newmap[key] = value
print(newmap)
输出如下:
{'0x9476': 6, '0x958f': 4, '0x993c': 8, '0x9a4b': 3, '0x9e3a': 7, '0x9ea3': 2, '0x9f64': 5, '0x9f92': 1, '0x9fa4': 0, '0x9fa5': 9}
现在就可以把页面上的自定义字体替换成正常字体,再解析需要的字段,Scrapy实现的全部代码如下:
import scrapy
from items import Com58FanLoder
from items import FanInfoItem
import re, base64, io
from scrapy.selector import Selector
from fontTools.ttLib import TTFont
class Com58Spider(scrapy.Spider):
# 只列出parse函数
def parse_fan(self, response):
# 获取加密字符串
base64_str = re.search(r"base64,(.*?)'\)", response.text).group(1)
b = base64.b64decode(base64_str)
font = TTFont(io.BytesIO(b))
bestcmap = font['cmap'].getBestCmap()
newmap = dict()
for key in bestcmap.keys():
value = int(re.search(r'(\d+)', bestcmap[key]).group(1)) - 1
key = hex(key)
newmap[key] = value
# 把页面上自定义字体替换成正常字体
__response = response.text
for key, value in newmap.items():
key = key.replace('0x', '&#x') + ';'
if key in __response:
__response = __response.replace(key, str(value))
selector = Selector(text=__response)
# 与上面分开,上面解析字体反爬
item_loader = Com58FanLoder(item=FanInfoItem(), response=response)
item_loader.add_xpath('house_title', '//div[@class="house-title"]/h1/text()')
item_loader.add_value('house_price', selector.xpath('//p[@class="house-basic-item1"]/span[1]').extract_first())
item_loader.add_value('unit_price', selector.xpath('//p[@class="house-basic-item1"]/span[2]/text()').
extract_first().replace('\xa0', '')) # replace('\xa0', '')的原因是因为有一个空格,导致显示不正常,直接剔除即可
解析结果,圈出的部分就是上述代码的提取结果:
当然,给出用requests解析的代码,感谢python解析字体反爬博主:
import requests
import re, base64, io
from lxml import etree
from fontTools.ttLib import TTFont
# 待解析的url
url = r'https://sz.58.com/chuzu/'
headers = {
'User-Agent':'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)'
}
response = requests.get(url=url, headers=headers)
# 获取加密字符串
base64_str = re.search("base64,(.*?)'\)", response.text).group(1)
b = base64.b64decode(base64_str)
font = TTFont(io.BytesIO(b))
bestcmap = font['cmap'].getBestCmap()
newmap = dict()
for key in bestcmap.keys():
value = int(re.search(r'(\d+)', bestcmap[key]).group(1)) - 1
key = hex(key)
newmap[key] = value
# 把页面上自定义字体替换成正常字体
response_ = response.text
for key,value in newmap.items():
key_ = key.replace('0x','&#x') + ';'
if key_ in response_:
response_ = response_.replace(key_,str(value))
# 获取标题
rec = etree.HTML(response_)
lis = rec.xpath('//ul[@class="listUl"]/li')
for li in lis:
title = li.xpath('./div[@class="des"]/h2/a/text()')
if title:
title = title[0]
print(title)
参考:
python解析字体反爬 https://www.cnblogs.com/eastonliu/p/9925652.html
推荐阅读:
Python爬虫六:字体反爬处理(猫眼+汽车之家)-2018.10 https://blog.csdn.net/xing851483876/article/details/82928607?tdsourcetag=s_pctim_aiomsg
爬虫遇见诡异字体-反反爬(58同城字体) https://www.jianshu.com/p/487bb2f20641