python爬虫爬取pdf_Python 爬虫:爬取教程生成 PDF
作為一名程序員,經常要搜一些教程,有的教程是在線的,不提供離線版本,這就有些局限了。那么同樣作為一名程序員,遇到問題就應該解決它,今天就來將在線教程保存為PDF以供查閱。
1、網站介紹
之前再搜資料的時候經常會跳轉到如下圖所示的在線教程:
01.教程樣式
包括一些github的項目也紛紛將教程鏈接指向這個網站。經過一番查找,該網站是一個可以創建、托管和瀏覽文檔的網站,其網址為:https://readthedocs.org 。在上面可以找到很多優質的資源。
該網站雖然提供了下載功能,但是有些教程并沒有提供PDF格式文件的下載,如圖:
02.下載
該教程只提供了 HTML格式文件的下載,還是不太方便查閱,那就讓我們動手將其轉成PDF吧!
2、準備工作
2.1 軟件安裝
由于我們是要把html轉為pdf,所以需要手動wkhtmltopdf 。Windows平臺直接在 http://wkhtmltopdf.org/downloads.html53 下載穩定版的 wkhtmltopdf 進行安裝,安裝完成之后把該程序的執行路徑加入到系統環境 $PATH 變量中,否則 pdfkit 找不到 wkhtmltopdf 就出現錯誤 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行進行安裝
$ sudo apt-get install wkhtmltopdf # ubuntu
$ sudo yum intsall wkhtmltopdf # centos
2.2 庫安裝
pip install requests # 用于網絡請求
pip install beautifulsoup4 # 用于操作html
pip install pdfkit # wkhtmltopdf 的Python封裝包
pip install PyPDF2 # 用于合并pdf
3、爬取內容
3.1 獲取教程名稱
頁面的左邊一欄為目錄,按F12調出開發者工具并按以下步驟定位到目錄元素:
① 點擊開發者工具左上角"選取頁面元素"按鈕;
② 用鼠標點擊左上角教程名稱處。
通過以上步驟即可定位到目錄元素,用圖說明:
03.尋找教程名稱
從圖看到我們需要的教程名稱包含在
book_name = soup.find('div', class_='wy-side-nav-search').a.text
3.2 獲取目錄及對應網址
使用與 2.1 相同的步驟來獲取:
04.定位目錄及網址
從圖看到我們需要的目錄包含在
標簽里為一級目錄及網址;標簽里為二級目錄及網址。當然這個url是相對的url,前面還要拼接http://python3-cookbook.readthedocs.io/zh_CN/latest/。使用BeautifulSoup進行數據的提取:
# 全局變量
base_url = 'http://python3-cookbook.readthedocs.io/zh_CN/latest/'
book_name = ''
chapter_info = []
def parse_title_and_url(html):
"""
解析全部章節的標題和url
:param html: 需要解析的網頁內容
:return None
"""
soup = BeautifulSoup(html, 'html.parser')
# 獲取書名
book_name = soup.find('div', class_='wy-side-nav-search').a.text
menu = soup.find_all('div', class_='section')
chapters = menu[0].div.ul.find_all('li', class_='toctree-l1')
for chapter in chapters:
info = {}
# 獲取一級標題和url
# 標題中含有'/'和'*'會保存失敗
info['title'] = chapter.a.text.replace('/', '').replace('*', '')
info['url'] = base_url + chapter.a.get('href')
info['child_chapters'] = []
# 獲取二級標題和url
if chapter.ul is not None:
child_chapters = chapter.ul.find_all('li')
for child in child_chapters:
url = child.a.get('href')
# 如果在url中存在'#',則此url為頁面內鏈接,不會跳轉到其他頁面
# 所以不需要保存
if '#' not in url:
info['child_chapters'].append({
'title': child.a.text.replace('/', '').replace('*', ''),
'url': base_url + child.a.get('href'),
})
chapter_info.append(info)
代碼中定義了兩個全局變量來保存信息。章節內容保存在chapter_info列表里,里面包含了層級結構,大致結構為:
[
{
'title': 'first_level_chapter',
'url': 'www.xxxxxx.com',
'child_chapters': [
{
'title': 'second_level_chapter',
'url': 'www.xxxxxx.com',
}
...
]
}
...
]
3.3 獲取章節內容
還是同樣的方法定位章節內容:
05.獲取章節內容
代碼中我們通過itemprop這個屬性來定位,好在一級目錄內容的元素位置和二級目錄內容的元素位置相同,省去了不少麻煩。
html_template = """
{content}
"""
def get_content(url):
"""
解析URL,獲取需要的html內容
:param url: 目標網址
:return: html
"""
html = get_one_page(url)
soup = BeautifulSoup(html, 'html.parser')
content = soup.find('div', attrs={'itemprop': 'articleBody'})
html = html_template.format(content=content)
return html
3.4 保存pdf
def save_pdf(html, filename):
"""
把所有html文件保存到pdf文件
:param html: 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_string(html, filename, options=options)
def parse_html_to_pdf():
"""
解析URL,獲取html,保存成pdf文件
:return: None
"""
try:
for chapter in chapter_info:
ctitle = chapter['title']
url = chapter['url']
# 文件夾不存在則創建(多級目錄)
dir_name = os.path.join(os.path.dirname(__file__), 'gen', ctitle)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
html = get_content(url)
padf_path = os.path.join(dir_name, ctitle + '.pdf')
save_pdf(html, os.path.join(dir_name, ctitle + '.pdf'))
children = chapter['child_chapters']
if children:
for child in children:
html = get_content(child['url'])
pdf_path = os.path.join(dir_name, child['title'] + '.pdf')
save_pdf(html, pdf_path)
except Exception as e:
print(e)
3.5 合并pdf
經過上一步,所有章節的pdf都保存下來了,最后我們希望留一個pdf,就需要合并所有pdf并刪除單個章節pdf。
```python
from PyPDF2 import PdfFileReader, PdfFileWriter
def merge_pdf(infnList, outfn):
"""
合并pdf
:param infnList: 要合并的PDF文件路徑列表
:param outfn: 保存的PDF文件名
:return: None
"""
pagenum = 0
pdf_output = PdfFileWriter()
for pdf in infnList:
# 先合并一級目錄的內容
first_level_title = pdf['title']
總結
以上是生活随笔為你收集整理的python爬虫爬取pdf_Python 爬虫:爬取教程生成 PDF的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为充电的效果_华为充电特效主题插件下载
- 下一篇: 遗传算法中常用的选择策略