本篇内容介绍了“Python怎么爬取论坛文章保存成PDF”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
Python 3.6
Pycharm
wkhtmltopdf
pdfkit
requests
parsel
安装Python并添加到环境变量,pip安装需要的相关模块即可。
将CSDN这上面的文章内容爬取保存下来,保存成PDF的格式。
如果想要把网页文章内容保存成PDF,首先你要下载一个软件 wkhtmltopdf 不然你是没有办法实现的。可以自行去百度搜索下载,也可以找上面的 交流群 下载。
前几篇文章已经讲了,关于文字方面的爬取方式,对于爬取文本内容还是没有难度了吧。
想要获取文章内容,首先就要爬取每篇文章的url地址。
具体分析的流程之前的文章也有分享过,这里就跳过了。
python爬取CSDN博客文章并制作成PDF文件
import pdfkit
import requests
import parsel
html_str = """
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
{article}
</body>
</html>
"""
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)
def main(html_url):
# 请求头
headers = {
"Host": "blog.csdn.net",
"Referer": "https://blog.csdn.net/qq_41359265/article/details/102570971",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
}
# 用户信息
cookie = {
'Cookie': '你自己的cookie'
}
response = requests.get(url=html_url, headers=headers, cookies=cookie)
selector = parsel.Selector(response.text)
urls = selector.css('.article-list h5 a::attr(href)').getall()
for html_url in urls:
response = requests.get(url=html_url, headers=headers, cookies=cookie)
# text 文本(字符串)
# 遭遇了反扒
# print(response.text)
"""如何把 HTML 变成 PDF 格式"""
# 提取文章部分
sel = parsel.Selector(response.text)
# css 选择器
article = sel.css('article').get()
title = sel.css('h2::text').get()
save(article, title)
if __name__ == '__main__':
url = 'https://blog.csdn.net/fei347795790/article/list/1'
main(url)
“Python怎么爬取论坛文章保存成PDF”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4848094/blog/4934654