国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現抓取HTML網頁并以PDF文件形式保存的方法

2020-02-23 00:04:06
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現抓取HTML網頁并以PDF文件形式保存的方法。分享給大家供大家參考,具體如下:

一、前言

今天介紹將HTML網頁抓取下來,然后以PDF保存,廢話不多說直接進入教程。

今天的例子以廖雪峰老師的Python教程網站為例:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

二、準備工作

1. PyPDF2的安裝使用(用來合并PDF):

PyPDF2版本:1.25.1

https://pypi.python.org/pypi/PyPDF2/1.25.1

https://github.com/mstamy2/PyPDF2

安裝:

pip install PyPDF2

使用示例:

from PyPDF2 import PdfFileMergermerger = PdfFileMerger()input1 = open("hql_1_20.pdf", "rb")input2 = open("hql_21_40.pdf", "rb")merger.append(input1)merger.append(input2)# Write to an output PDF documentoutput = open("hql_all.pdf", "wb")merger.write(output)

2. requests、beautifulsoup 是爬蟲兩大神器,reuqests 用于網絡請求,beautifusoup 用于操作 html 數據。有了這兩把梭子,干起活來利索。scrapy 這樣的爬蟲框架我們就不用了,這樣的小程序派上它有點殺雞用牛刀的意思。此外,既然是把 html 文件轉為 pdf,那么也要有相應的庫支持, wkhtmltopdf 就是一個非常的工具,它可以用適用于多平臺的 html 到 pdf 的轉換,pdfkit 是 wkhtmltopdf 的Python封裝包。首先安裝好下面的依賴包

pip install requestspip install beautifulsoup4pip install pdfkit

3. 安裝 wkhtmltopdf

Windows平臺直接在 http://wkhtmltopdf.org/downloads.html 下載穩定版的 wkhtmltopdf 進行安裝,安裝完成之后把該程序的執行路徑加入到系統環境 $PATH 變量中,否則 pdfkit 找不到 wkhtmltopdf 就出現錯誤 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行進行安裝

$ sudo apt-get install wkhtmltopdf # ubuntu$ sudo yum intsall wkhtmltopdf   # centos

三、數據準備

1. 獲取每篇文章的url

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

2. 通過文章url用模板保存每篇文章的HTML文件

html模板:

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內容  :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]    # 標題    title = soup.find('h4').get_text()    # 標題加入到正文的最前面,居中顯示    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標簽的src相對路徑的改成絕對路徑    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:    logging.error("解析錯誤", exc_info=True)            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 镇坪县| 南昌市| 江油市| 六枝特区| 北宁市| 斗六市| 十堰市| 顺义区| 花莲市| 平泉县| 涿鹿县| 神农架林区| 武强县| 扎兰屯市| 闽侯县| 高安市| 佛坪县| 临清市| 乐亭县| 宝鸡市| 绍兴县| 维西| 道真| 靖江市| 衡阳县| 弥渡县| 如皋市| 宿松县| 孟州市| 泸溪县| 德阳市| 剑川县| 扎囊县| 佛坪县| 陆丰市| 忻城县| 远安县| 四平市| 武清区| 明溪县| 万盛区|