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

前言

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

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

https://space.bilibili.com/523606542

前文内容

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

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

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

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

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

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

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

基本开发环境

  • Python 3.6
  • Pycharm
  • wkhtmltopdf

相关模块的使用

  • pdfkit
  • requests
  • parsel

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

1、目标需求

 


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

2、网页数据分析

若是想要把网页文章内容保存成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)

 

 

 

相关文章
相关标签/搜索