接上一篇文章, 项目实战 | 手把手带你获取某知识付费平台精华帖,并制作电子书(一)还有一些遗留问题,我说了上篇文章只是牛刀小试,这一篇文章会进一步优化.
上一篇文章的问题:
这篇文章解决了几个问题
好了,开始我的表演, 先给效果图!
先做一个html网页模板,下面会介绍这个模板,这个模板中插入,标题,作者时间,正文,以及图片
self.html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>{title}</h1>
<h6>{author_time}</h6>
<p font-size = '35px'>{text}</p>
<img src = {images}>
</body>
</html>
"""
接着用我们抓取到的标题,作者时间,正文,图片来填充这个模板,并把这些内容填充到一个内容数组中.
if topic.get('type') == 'talk' and topic.get('talk'): # 会话模式的
text = topic.get('talk').get('text').replace('\n', '') # 获取正文内容
title = text[0:20] if len(text) > 20 else text
author = topic.get('talk').get('owner').get('name') # 获取作者名称
create_time = (topic.get('create_time')[:20]).replace('T', ' ') # 获取最后更新时间
author_time = '{}在{}发表'.format(author, create_time)
images = topic.get('talk').get('images') # 获取图片列表
img = []
if images is not None:
for image in images:
img = image.get('large').get('url')
# img.append(image.get('large').get('url'))
title = title if len(title) > 0 else '无标题'
html_content = self.html_template.format(title=title, author_time=author_time, text=text,
images=img)
self.html_contents.append(html_content)
把内容列表转换成文件列表,然后用pdfkit工具传化成pdf文件. 这里需要安装两个包一个是pdfkit,另一个是wkhtmltopdf,
其中 wkhtmltopdf工具是一个exe文件,然后要指定这个文件
self.config = pdfkit.configuration(
wkhtmltopdf='C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe') # 这里需要配置一下wkhtmlpdf.exe路径
# 下面是把内容列表转化成文件列表,然后用pdfkit转换成pdf文件,与此同时目录也会自动生成.
def creat_pdf_file(self, group_title):
htmls = [] # 这里是存放html文件
for index, file in enumerate(self.html_contents):
html = '{}.html'.format(index)
with open(html, 'w', encoding='utf-8') as f: # 点击open函数查看用法,这里是写入不要搞错了
f.write(file)
htmls.append(html)
try:
output_file = 'D:/zsxq2/{}.pdf'.format(group_title)
if not os.path.exists(output_file): # 过滤掉重复文件
pdfkit.from_file(htmls, output_file, configuration=self.config) # 注意这里需要配置一下wkhtmltopdf
except Exception as e:
print(e)
self.html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>{title}</h1>
<h6>{author_time}</h6>
<p>{text}</p>
<img src = {images}> # 注意这里传入图片的url,但是怎么传入多张,我还没有弄明白,不是很熟动态插入代码
</body>
</html>
"""
这里向html模板中插入标题,作者与时间,然后帖子正文内容,以及图片
html_content = self.html_template.format(title=title, author_time=author_time, text=text,
images=img)
很容易通过浏览器的调试模式找到普通帖子的链接,然后直接获取数据.这里我的函数中添加了一个type字段来控制是获取精华帖子还是普通帖子
# 精华帖子
url_content_essence = 'https://api.zsxq.com/v1.10/groups/{}/topics?scope=digests&count=20&end_time={}'.format(
group_id,
self.end_time)
# 普通帖子
url_content_normal = 'https://api.zsxq.com/v1.10/groups/{}/topics?count=20&end_time={}'.format(
group_id,
self.end_time)
response = requests.get(url=url_content_essence if type > 0 else url_content_normal,
headers=self.zsxq_headers) # 一定要加headers,规范写法,就像过马路一样穿红灯有时没事,有时要命!
其实我们知道,星球中很多内容是由链接构成的,而我们又知道pdf 支持链接的点击,所以我决定把链接加上.方便点击链接,另外像我加入了七十多个星球了,我想加快电子书制作速度,这里就要用到多线程. 还有每个帖子动态只插入了一张图片,其实帖子中可能有多张图片,这里我还需要进一步优化. 总之要优化的就4个地方
猜你喜欢
项目实战 | 手把手带你获取某知识付费平台精华帖,并制作电子书(一)