序文
少し前に、Bという名前の人にビデオを投稿しました。つまり、自分の記事を収集してPDF形式のチュートリアルに変換しました。CSDNが実際に報告してくれました。!!
今度は自分で記事を書いて、それをPDF形式の電子形式に変換して、送信できるかどうかを確認します。
wkhtmltopdf [ソフトウェア]、これを学ぶ必要があります。そうしないと、このケースを実現できません。
記事のコンテンツコードを取得する
- リクエストを送信し、URLアドレスのリクエストを送信します
- データを解析し、コンテンツを抽出します
- データを保存し、最初にhtmlファイルとして保存します
- HTMLファイルをPDFに変換する
#コード
リクエストデータ
import requests # 数据请求模块
url = f'https://blog.csdn.net/fei347795790/article/list/1' # 确定请求网址
# headers 请求头, 主要用于伪装python, 防止程序被服务器识别出来
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36'
}
# 用requests模块里面get方式发送请求
response = requests.get(url=url, headers=headers)
print(response.text)
<応答[200]>応答オブジェクト200は、要求が成功したことを示します
データを解析し、コンテンツを抽出します
for index in href:
html_data = requests.get(url=index, headers=headers).text
selector_1 = parsel.Selector(html_data)
title = selector_1.css('#articleContentId::text').get()
content = selector_1.css('#content_views').get()
article_content = html_str.format(article=content)
print(title)
print(article_content)
break
データを保存する
html_path = 'html\\' + title +'.html'
with open(html_path, mode='w', encoding=' utf-8') as f:
f.write(article_content)
print(title,'保存成功')
PDFファイルに変換
html_path = 'html\\ + title + '.html'
pdf_path = 'pdf\\' + title + '.pdf'
with open(html_path, mode='w', encoding='utf-8') as f:
f.write(article_content)
config = pdfkit.configuration(wkhtmltopdf=r'C:\01-Software-installation\wkhtmltopdf\bin\wkhtmltopdf.exe')
ppdfkit.from_file(html_path,pdf_path,configuration=config)
print(title,'保存成功')