python爬取網(wǎng)頁(yè)內(nèi)容轉(zhuǎn)換為PDF文件
本文實(shí)例為大家分享了python爬取網(wǎng)頁(yè)內(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()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- python爬蟲爬取指定內(nèi)容的解決方法
- python爬蟲爬取bilibili網(wǎng)頁(yè)基本內(nèi)容
- Python爬蟲爬取百度搜索內(nèi)容代碼實(shí)例
- python爬蟲開發(fā)之使用python爬蟲庫(kù)requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實(shí)例
- python爬取內(nèi)容存入Excel實(shí)例
- Python爬蟲爬取新浪微博內(nèi)容示例【基于代理IP】
- Python下使用Scrapy爬取網(wǎng)頁(yè)內(nèi)容的實(shí)例
- 基于Python實(shí)現(xiàn)web網(wǎng)頁(yè)內(nèi)容爬取的方法
相關(guān)文章
python驗(yàn)證碼識(shí)別實(shí)例代碼
這篇文章主要介紹了python驗(yàn)證碼識(shí)別實(shí)例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02Python 按比例獲取樣本數(shù)據(jù)或執(zhí)行任務(wù)的實(shí)現(xiàn)代碼
這篇文章主要介紹了Python 按比例獲取樣本數(shù)據(jù)或執(zhí)行任務(wù),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12Pycharm以root權(quán)限運(yùn)行腳本的方法
今天小編就為大家分享一篇Pycharm以root權(quán)限運(yùn)行腳本的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01python使用collections模塊的容器數(shù)據(jù)類型高效處理數(shù)據(jù)
這篇文章主要為大家介紹了python使用collections模塊的容器數(shù)據(jù)類型高效處理數(shù)據(jù)的方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06Django filter動(dòng)態(tài)過濾與排序?qū)崿F(xiàn)過程解析
這篇文章主要介紹了Django filter動(dòng)態(tài)過濾與排序?qū)崿F(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11Java中MultipartFile與File互轉(zhuǎn)的實(shí)現(xiàn)
本文主要介紹了Java中MultipartFile與File互轉(zhuǎn)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03Keras實(shí)現(xiàn)支持masking的Flatten層代碼
這篇文章主要介紹了Keras實(shí)現(xiàn)支持masking的Flatten層代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06