Python怎么爬取论坛文章保存成PDF

发布时间:2021-11-23 11:24:28 作者:iii
来源:亿速云 阅读:198

本篇内容介绍了“Python怎么爬取论坛文章保存成PDF”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

基本开发环境

相关模块的使用

安装Python并添加到环境变量,pip安装需要的相关模块即可。

一、目标需求

将CSDN这上面的文章内容爬取保存下来,保存成PDF的格式。

二、网页数据分析

如果想要把网页文章内容保存成PDF,首先你要下载一个软件 wkhtmltopdf 不然你是没有办法实现的。可以自行去百度搜索下载,也可以找上面的 交流群 下载。

Python怎么爬取论坛文章保存成PDF


前几篇文章已经讲了,关于文字方面的爬取方式,对于爬取文本内容还是没有难度了吧。

想要获取文章内容,首先就要爬取每篇文章的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

Python怎么爬取论坛文章保存成PDF

“Python怎么爬取论坛文章保存成PDF”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. 使用python怎么爬取微信公众号文章
  2. python爬取网页转换为PDF文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python多线程爬虫的使用方法是什么

下一篇:c语言怎么实现含递归清场版扫雷游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》