python爬蟲學習(3)-抓取廖雪峰python教程並製作成PDF文件
實現功能:抓取廖雪峰網站的python教程,儲存html頁面到本地,然後用pdfkit包將html轉換為pdf。
執行需求:安裝python的pdfkit包和windows下的wkhtmltopdf。
程式碼如下:
# -*- coding: utf-8
import urllib2
import urllib
import re,os
import time
import pdfkit
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Liao:
def __init__(self,init_url,out_put_path):
self.init_url = init_url
self.out_put_path = out_put_path
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
self.headers = { 'User-Agent' : self.user_agent }
self.file_name = 'liao.pdf'
self.html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gb2312">
</head>
<body>
{content}
</body>
</html>
"""
#獲取網頁內容
def get_content(self,url):
try:
request = urllib2.Request(url,headers=self.headers)
response = urllib2.urlopen(request)
content = response.read().decode('utf-8').encode('GBK')
return content
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u"連線頁面失敗,錯誤原因",e.reason
return None
#獲取文章目錄url列表
def get_article_url(self):
content = self.get_content(self.init_url)
#print content
pattern = re.compile(r'<li id="\d.*?" style="margin-left:(\d)em;">.*?<a href="(.*?)">(.*?)</a>.*?</li>',re.S)
# pattern = re.compile(r'<li id="(\d.*?)" style="margin-left:\dem;">',re.S)
result = re.findall(pattern,content)
i = 1
print len(result)
# for x in result:
# print x[0],x[1]
# i+=1
return result
#獲取文章內容,傳入文章的url,返回文章內容
def get_article_detail(self):
url_list = self.get_article_url()
pattern = re.compile(r'<div class="x-wiki-content">(.*?)</div>',re.S)
# patt_title = re.compile(r'<h4>(.*?)</h4>')
patt_img = re.compile(r'<img src="(/files/attachments/.*?)"',re.S)
i = 1
urls = []
for item in url_list:
#獲取文章的url
article_url = 'http://www.liaoxuefeng.com' + item[1]
url_ind = article_url.split('/')[-1]
#提取文章標題
article_title = item[2].replace('/','_')
title_level = item[0]
#title_tag = '<center><h' + title_level + '>' + article_title + '</h' + title_level + '></center>'
title_tag = '<center><h1>' + article_title + '</h></center>'
#生成html檔名
html_file = url_ind + '.html'
#根據文章url,抓取文章內容
content = self.get_content(article_url)
article_content = str(re.findall(pattern,content)[0])
#處理圖片的url,加上域名
def func(m):
if not m.group(1).startswith("http"):
rtn = '<img src="http://www.liaoxuefeng.com' + m.group(1) + '"'
return rtn
else:
return '<img src="' + m.group(1) + '"'
article_content = re.compile(patt_img).sub(func, article_content)
#將標題加到文章內容中
article_content = title_tag + article_content
article_content = self.html_template.format(content=article_content)
#生成url及檔名列表
urls.append((url_ind,html_file))
#寫檔案
print 'saving file ' + html_file
with open(html_file, 'wb') as f:
f.write(article_content)
return urls
#將html儲存成pdf
def save_pdf(self,htmls):
"""
把所有html檔案儲存到pdf檔案
"""
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'custom-header': [
('Accept-Encoding', 'gzip')
]
}
pdfkit.from_file(htmls, self.file_name, options=options)
init_url = 'http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000'
out_put_path = 'd:/python/test/output'
liao = Liao(init_url,out_put_path)
urls = liao.get_article_detail()
htmls = [x[1] for x in urls]
liao.save_pdf(htmls)
執行需求:安裝python的pdfkit包和windows下的wkhtmltopdf。
程式碼如下:
# -*- coding: utf-8
import urllib2
import urllib
import re,os
import time
import pdfkit
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Liao:
def __init__(self,init_url,out_put_path):
self.init_url = init_url
self.out_put_path = out_put_path
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
self.headers = { 'User-Agent' : self.user_agent }
self.file_name = 'liao.pdf'
self.html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gb2312">
</head>
<body>
{content}
</body>
</html>
"""
#獲取網頁內容
def get_content(self,url):
try:
request = urllib2.Request(url,headers=self.headers)
response = urllib2.urlopen(request)
content = response.read().decode('utf-8').encode('GBK')
return content
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u"連線頁面失敗,錯誤原因",e.reason
return None
#獲取文章目錄url列表
def get_article_url(self):
content = self.get_content(self.init_url)
#print content
pattern = re.compile(r'<li id="\d.*?" style="margin-left:(\d)em;">.*?<a href="(.*?)">(.*?)</a>.*?</li>',re.S)
# pattern = re.compile(r'<li id="(\d.*?)" style="margin-left:\dem;">',re.S)
result = re.findall(pattern,content)
i = 1
print len(result)
# for x in result:
# print x[0],x[1]
# i+=1
return result
#獲取文章內容,傳入文章的url,返回文章內容
def get_article_detail(self):
url_list = self.get_article_url()
pattern = re.compile(r'<div class="x-wiki-content">(.*?)</div>',re.S)
# patt_title = re.compile(r'<h4>(.*?)</h4>')
patt_img = re.compile(r'<img src="(/files/attachments/.*?)"',re.S)
i = 1
urls = []
for item in url_list:
#獲取文章的url
article_url = 'http://www.liaoxuefeng.com' + item[1]
url_ind = article_url.split('/')[-1]
#提取文章標題
article_title = item[2].replace('/','_')
title_level = item[0]
#title_tag = '<center><h' + title_level + '>' + article_title + '</h' + title_level + '></center>'
title_tag = '<center><h1>' + article_title + '</h></center>'
#生成html檔名
html_file = url_ind + '.html'
#根據文章url,抓取文章內容
content = self.get_content(article_url)
article_content = str(re.findall(pattern,content)[0])
#處理圖片的url,加上域名
def func(m):
if not m.group(1).startswith("http"):
rtn = '<img src="http://www.liaoxuefeng.com' + m.group(1) + '"'
return rtn
else:
return '<img src="' + m.group(1) + '"'
article_content = re.compile(patt_img).sub(func, article_content)
#將標題加到文章內容中
article_content = title_tag + article_content
article_content = self.html_template.format(content=article_content)
#生成url及檔名列表
urls.append((url_ind,html_file))
#寫檔案
print 'saving file ' + html_file
with open(html_file, 'wb') as f:
f.write(article_content)
return urls
#將html儲存成pdf
def save_pdf(self,htmls):
"""
把所有html檔案儲存到pdf檔案
"""
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'custom-header': [
('Accept-Encoding', 'gzip')
]
}
pdfkit.from_file(htmls, self.file_name, options=options)
init_url = 'http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000'
out_put_path = 'd:/python/test/output'
liao = Liao(init_url,out_put_path)
urls = liao.get_article_detail()
htmls = [x[1] for x in urls]
liao.save_pdf(htmls)
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10972173/viewspace-2133756/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Python 爬蟲:把廖雪峰的教程轉換成 PDF 電子書Python爬蟲
- 學以致用:Python爬取廖大Python教程製作pdfPython
- Python爬蟲學習系列教程Python爬蟲
- 跟著廖雪峰學python 005Python
- Python大牛廖雪峰13個案例帶你全面掌握商業爬蟲!Python爬蟲
- 【Python學習】爬蟲爬蟲爬蟲爬蟲~Python爬蟲
- 【廖雪峰python進階筆記】定製類Python筆記
- Python爬蟲抓取股票資訊Python爬蟲
- Python爬蟲系統化學習(3)Python爬蟲
- python爬蟲學習(1)-抓取糗事百科笑話Python爬蟲
- python爬蟲學習1Python爬蟲
- python爬蟲學習(2)-抓取百度貼吧內容Python爬蟲
- python爬蟲是什麼?學習python爬蟲難嗎Python爬蟲
- 《Python3網路爬蟲開發實戰》教程||爬蟲教程Python爬蟲
- 【廖雪峰python入門筆記】dictPython筆記
- 【廖雪峰python入門筆記】setPython筆記
- 【廖雪峰python入門筆記】切片Python筆記
- 【廖雪峰python入門筆記】迭代Python筆記
- 【廖雪峰python進階筆記】模組Python筆記
- 用Python爬蟲抓取代理IPPython爬蟲
- 【閱讀筆記】《Python3網路爬蟲開發實戰》PDF文件筆記Python爬蟲
- Python爬蟲入門教程 50-100 Python3爬蟲爬取VIP視訊-Python爬蟲6操作Python爬蟲
- 廖雪峰Git教程筆記Git筆記
- python如何實現簡單的爬蟲功能?Python學習教程!Python爬蟲
- python爬蟲抓取哈爾濱天氣資訊(靜態爬蟲)Python爬蟲
- Python爬蟲新手教程:手機APP資料抓取 pyspiderPython爬蟲APPIDE
- 為什麼學習python及爬蟲,Python爬蟲[入門篇]?Python爬蟲
- python爬蟲開發微課版pdf_Python爬蟲開發實戰教程(微課版)Python爬蟲
- python爬蟲學習:爬蟲QQ說說並生成詞雲圖,回憶滿滿Python爬蟲
- [雪峰磁針石部落格]python爬蟲cookbook1爬蟲入門Python爬蟲
- 【廖雪峰python入門筆記】函式Python筆記函式
- 【廖雪峰python入門筆記】變數Python筆記變數
- 【廖雪峰python入門筆記】if語句Python筆記
- 【廖雪峰python入門筆記】for迴圈Python筆記
- 廖雪峰《Python3 基礎教程》讀書筆記——第一、第二章Python筆記
- python3網路爬蟲開發實戰pdfPython爬蟲
- Python爬蟲抓取技術的門道Python爬蟲
- python爬蟲之抓取小說(逆天邪神)Python爬蟲