小说推文之小说内容获取,即小说网站爬取(爬虫遇到字体加密)
由于原始代码已经非常接近完成,以下是一个简化的示例,展示如何修改原始代码以应对字体加密问题:
import requests
from bs4 import BeautifulSoup
from fontTools.ttLib import TTFont
import re
import urllib.request
def get_novel_content(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.text
return None
def download_font(font_url):
font_path = font_url.split('/')[-1]
urllib.request.urlretrieve(font_url, font_path)
return font_path
def decrypt_content(content, font_path):
ttfont = TTFont(font_path)
cmap = ttfont['cmap'].getBestCmap()
reg = re.compile(r'\\u([0-9a-fA-F]{4})')
unicode_list = reg.findall(content)
decrypted_content = ''
for unicode_str in unicode_list:
decrypted_content += chr(cmap[int(unicode_str, 16)])
return decrypted_content
def main():
url = 'http://www.******.com/109609.html' # 小说章节链接
html_content = get_novel_content(url)
if html_content:
soup = BeautifulSoup(html_content, 'html.parser')
font_url = soup.find('link', {'rel': 'stylesheet'}).get('href')
font_path = download_font(font_url)
content = soup.find('div', {'id': 'content'})
if content:
encrypted_content = str(content)
decrypted_content = decrypt_content(encrypted_content, font_path)
print(decrypted_content)
if __name__ == '__main__':
main()
这段代码首先定义了获取小说内容、下载字体文件和解密内容的函数。在main
函数中,它先获取了网页内容,然后提取字体链接并下载,接着解密小说内容并打印出来。注意,由于字体加密解密涉及版权问题,这里的解密方法可能不适用于所有网站,仅供学习参考。
评论已关闭