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)

 

 

 

相關文章
相關標籤/搜索