前言
本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。
基本开发环境
Python 3.6
Pycharm
相关模块的使用
import parselimport requestsimport pdfkit
一、明确需求
将百度百科上面所看到的内容保存成PDF。
二、网页数据分析以及代码实现
https://baike.baidu.com/feiyi?fr=dhlfeiyi
这个网址包含了非物质遗产的百科词条信息。
通过开发者工具可以查找到相关的json数据包。
需要注意:
接口是post请求,不是get请求;
filterTags 参数的是根据类目的变化而改变的。[0,类目ID]
page 对应的页码
获取所有词条url链接
for page in range(0, 69): url = 'https://baike.baidu.com/wikitag/api/getlemmas' data = { 'limit': '20', 'timeout': '3000', 'filterTags': '[0,0]', 'tagId': '71394', 'fromLemma': 'false', 'contentLength': '40', 'page': page, } headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } response = requests.post(url=url, data=data, headers=headers) lemmaList = response.json()['lemmaList'] for i in lemmaList: lemmaUrl = i['lemmaUrl']
如果想要保存成PDF,是需要wkhtmltopdf软件的。
可以在公众号后台私信<210127百度百科>
百度百科的词条页面是静态网页,可以直接获取词条内容。
获取词条内容以及标题
def main(html_url): resp_lemma = requests.post(url=html_url, headers=headers) selector = parsel.Selector(resp_lemma.text) article = selector.css('div.main-content').get() title = selector.css('.lemmaWgt-lemmaTitle-title h1::text').get() save(article, title)
保存文件
html_str = """ Document{article}"""def save(article, title): pdf_path = 'pdf\\' + title + '.pdf' html_path = 'html\\' + title + '.html' html = html_str.format(article=article) with open(html_path, mode='w', encoding='utf-8') as f: f.write(html) print('{}已下载完成'.format(title)) # exe 文件存放的路径 config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') # 把 html 通过 pdfkit 变成 pdf 文件 pdfkit.from_file(html_path, pdf_path, configuration=config)
下载部分实现效果