Python爬虫新手入门教学(八):爬取论坛文章保存成PDF

前言

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理。

Python爬虫、数据分析、网站开发等案例教程视频免费在线观看

https://space.bilibili.com/523606542

前文内容

Python爬虫新手入门教学(一):爬取豆瓣电影排行信息

Python爬虫新手入门教学(二):爬取小说

Python爬虫新手入门教学(三):爬取链家二手房数据

Python爬虫新手入门教学(四):爬取前程无忧招聘信息

Python爬虫新手入门教学(五):爬取B站视频弹幕

Python爬虫新手入门教学(六):制作词云图

Python爬虫新手入门教学(七):爬取腾讯视频弹幕

基本开发环境

  • 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 h4 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('h1::text').get()
        save(article, title)


if __name__ == '__main__':
    url = 'https://blog.csdn.net/fei347795790/article/list/1'
    main(url)

猜你喜欢

转载自blog.csdn.net/m0_48405781/article/details/113336829