python爬取網(wǎng)頁內(nèi)容轉(zhuǎn)換為PDF文件
本文實(shí)例為大家分享了python爬取網(wǎng)頁內(nèi)容轉(zhuǎn)換為PDF的具體代碼,供大家參考,具體內(nèi)容如下
將廖雪峰的學(xué)習(xí)教程轉(zhuǎn)換成PDF文件,代碼只適合該網(wǎng)站,如果需要其他網(wǎng)站的教程,可靠需要進(jìn)行稍微的修改。
# coding=utf-8
import os
import re
import time
import pdfkit
import requests
from bs4 import BeautifulSoup
from PyPDF2 import PdfFileMerger
import sys
reload(sys)
sys.setdefaultencoding('utf8')
html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
{content}
</body>
</html>
"""
#----------------------------------------------------------------------
def parse_url_to_html(url, name):
"""
解析URL,返回HTML內(nèi)容
:param url:解析的url
:param name: 保存的html文件名
:return: html
"""
try:
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 正文
body = soup.find_all(class_="x-wiki-content")[0]
# 標(biāo)題
title = soup.find('h4').get_text()
# 標(biāo)題加入到正文的最前面,居中顯示
center_tag = soup.new_tag("center")
title_tag = soup.new_tag('h1')
title_tag.string = title
center_tag.insert(1, title_tag)
body.insert(1, center_tag)
html = str(body)
# body中的img標(biāo)簽的src相對(duì)路徑的改成絕對(duì)路徑
pattern = "(<img .*?src=\")(.*?)(\")"
def func(m):
if not m.group(3).startswith("http"):
rtn = m.group(1) + "http://www.liaoxuefeng.com" + m.group(2) + m.group(3)
return rtn
else:
return m.group(1)+m.group(2)+m.group(3)
html = re.compile(pattern).sub(func, html)
html = html_template.format(content=html)
html = html.encode("utf-8")
with open(name, 'wb') as f:
f.write(html)
return name
except Exception as e:
print "解析錯(cuò)誤!"
#----------------------------------------------------------------------
def get_url_list():
"""
獲取所有URL目錄列表
:return:
"""
response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")
soup = BeautifulSoup(response.content, "html.parser")
menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]
urls = []
for li in menu_tag.find_all("li"):
url = "http://www.liaoxuefeng.com" + li.a.get('href')
urls.append(url)
return urls
#----------------------------------------------------------------------
def save_pdf(htmls, file_name):
"""
把所有html文件保存到pdf文件
:param htmls: html文件列表
:param file_name: pdf文件名
:return:
"""
options = {
'page-size': 'Letter',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8",
'custom-header': [
('Accept-Encoding', 'gzip')
],
'cookie': [
('cookie-name1', 'cookie-value1'),
('cookie-name2', 'cookie-value2'),
],
'outline-depth': 10,
}
pdfkit.from_file(htmls, file_name, options=options)
#----------------------------------------------------------------------
def main():
start = time.time()
file_name = u"liaoxuefeng_Python3_tutorial"
urls = get_url_list()
for index, url in enumerate(urls):
parse_url_to_html(url, str(index) + ".html")
htmls =[]
pdfs =[]
for i in range(0,124):
htmls.append(str(i)+'.html')
pdfs.append(file_name+str(i)+'.pdf')
save_pdf(str(i)+'.html', file_name+str(i)+'.pdf')
print u"轉(zhuǎn)換完成第"+str(i)+'個(gè)html'
merger = PdfFileMerger()
for pdf in pdfs:
merger.append(open(pdf,'rb'))
print u"合并完成第"+str(i)+'個(gè)pdf'+pdf
output = open(u"廖雪峰Python_all.pdf", "wb")
merger.write(output)
print u"輸出PDF成功!"
for html in htmls:
os.remove(html)
print u"刪除臨時(shí)文件"+html
for pdf in pdfs:
os.remove(pdf)
print u"刪除臨時(shí)文件"+pdf
total_time = time.time() - start
print(u"總共耗時(shí):%f 秒" % total_time)
#----------------------------------------------------------------------
def changeDir(dir_name):
"""
目錄切換
"""
if not os.path.exists(dir_name):
os.mkdir(dir_name)
os.chdir(dir_name)
#----------------------------------------------------------------------
if __name__ == '__main__':
#存放文件的路徑
dir_name = '/home/Python/Html'
changeDir(dir_name)
main()
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python爬蟲爬取指定內(nèi)容的解決方法
- python爬蟲爬取bilibili網(wǎng)頁基本內(nèi)容
- Python爬蟲爬取百度搜索內(nèi)容代碼實(shí)例
- python爬蟲開發(fā)之使用python爬蟲庫requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實(shí)例
- python爬取內(nèi)容存入Excel實(shí)例
- Python爬蟲爬取新浪微博內(nèi)容示例【基于代理IP】
- Python下使用Scrapy爬取網(wǎng)頁內(nèi)容的實(shí)例
- 基于Python實(shí)現(xiàn)web網(wǎng)頁內(nèi)容爬取的方法
相關(guān)文章
基于Python實(shí)現(xiàn)的ID3決策樹功能示例
這篇文章主要介紹了基于Python實(shí)現(xiàn)的ID3決策樹功能,簡單描述了ID3決策樹的相關(guān)概念,并結(jié)合實(shí)例形式分析了Python實(shí)現(xiàn)ID3決策樹的具體定義與使用技巧,需要的朋友可以參考下2018-01-01
Python實(shí)現(xiàn)Sqlite將字段當(dāng)做索引進(jìn)行查詢的方法
這篇文章主要介紹了Python實(shí)現(xiàn)Sqlite將字段當(dāng)做索引進(jìn)行查詢的方法,涉及Python針對(duì)sqlite數(shù)據(jù)庫索引操作的相關(guān)技巧,需要的朋友可以參考下2016-07-07
python實(shí)現(xiàn)身份證實(shí)名認(rèn)證的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于python實(shí)現(xiàn)身份證實(shí)名認(rèn)證的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
源碼解析python中randint函數(shù)的效率缺陷
這篇文章主要介紹了源碼解析python中randint函數(shù)的效率缺陷,通過討論?random?模塊的實(shí)現(xiàn),并討論了一些更為快速的生成偽隨機(jī)整數(shù)的替代方法展開主題,需要的盆友可以參考一下2022-06-06
使用python把Excel中的數(shù)據(jù)在頁面中可視化
最近學(xué)習(xí)數(shù)據(jù)分析,感覺Python做數(shù)據(jù)分析真的好用,下面這篇文章主要給大家介紹了關(guān)于如何使用python把Excel中的數(shù)據(jù)在頁面中可視化的相關(guān)資料,需要的朋友可以參考下2022-03-03

