python爬虫爬取pdf_Python 爬虫:爬取教程生成 PDF
作為一名程序員,經(jīng)常要搜一些教程,有的教程是在線的,不提供離線版本,這就有些局限了。那么同樣作為一名程序員,遇到問題就應(yīng)該解決它,今天就來將在線教程保存為PDF以供查閱。
1、網(wǎng)站介紹
之前再搜資料的時(shí)候經(jīng)常會(huì)跳轉(zhuǎn)到如下圖所示的在線教程:
01.教程樣式
包括一些github的項(xiàng)目也紛紛將教程鏈接指向這個(gè)網(wǎng)站。經(jīng)過一番查找,該網(wǎng)站是一個(gè)可以創(chuàng)建、托管和瀏覽文檔的網(wǎng)站,其網(wǎng)址為:https://readthedocs.org 。在上面可以找到很多優(yōu)質(zhì)的資源。
該網(wǎng)站雖然提供了下載功能,但是有些教程并沒有提供PDF格式文件的下載,如圖:
02.下載
該教程只提供了 HTML格式文件的下載,還是不太方便查閱,那就讓我們動(dòng)手將其轉(zhuǎn)成PDF吧!
2、準(zhǔn)備工作
2.1 軟件安裝
由于我們是要把html轉(zhuǎn)為pdf,所以需要手動(dòng)wkhtmltopdf 。Windows平臺(tái)直接在 http://wkhtmltopdf.org/downloads.html53 下載穩(wěn)定版的 wkhtmltopdf 進(jìn)行安裝,安裝完成之后把該程序的執(zhí)行路徑加入到系統(tǒng)環(huán)境 $PATH 變量中,否則 pdfkit 找不到 wkhtmltopdf 就出現(xiàn)錯(cuò)誤 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行進(jìn)行安裝
$ sudo apt-get install wkhtmltopdf # ubuntu
$ sudo yum intsall wkhtmltopdf # centos
2.2 庫安裝
pip install requests # 用于網(wǎng)絡(luò)請(qǐng)求
pip install beautifulsoup4 # 用于操作html
pip install pdfkit # wkhtmltopdf 的Python封裝包
pip install PyPDF2 # 用于合并pdf
3、爬取內(nèi)容
3.1 獲取教程名稱
頁面的左邊一欄為目錄,按F12調(diào)出開發(fā)者工具并按以下步驟定位到目錄元素:
① 點(diǎn)擊開發(fā)者工具左上角"選取頁面元素"按鈕;
② 用鼠標(biāo)點(diǎn)擊左上角教程名稱處。
通過以上步驟即可定位到目錄元素,用圖說明:
03.尋找教程名稱
從圖看到我們需要的教程名稱包含在
book_name = soup.find('div', class_='wy-side-nav-search').a.text
3.2 獲取目錄及對(duì)應(yīng)網(wǎng)址
使用與 2.1 相同的步驟來獲取:
04.定位目錄及網(wǎng)址
從圖看到我們需要的目錄包含在
標(biāo)簽里為一級(jí)目錄及網(wǎng)址;標(biāo)簽里為二級(jí)目錄及網(wǎng)址。當(dāng)然這個(gè)url是相對(duì)的url,前面還要拼接http://python3-cookbook.readthedocs.io/zh_CN/latest/。使用BeautifulSoup進(jìn)行數(shù)據(jù)的提取:
# 全局變量
base_url = 'http://python3-cookbook.readthedocs.io/zh_CN/latest/'
book_name = ''
chapter_info = []
def parse_title_and_url(html):
"""
解析全部章節(jié)的標(biāo)題和url
:param html: 需要解析的網(wǎng)頁內(nèi)容
: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 = {}
# 獲取一級(jí)標(biāo)題和url
# 標(biāo)題中含有'/'和'*'會(huì)保存失敗
info['title'] = chapter.a.text.replace('/', '').replace('*', '')
info['url'] = base_url + chapter.a.get('href')
info['child_chapters'] = []
# 獲取二級(jí)標(biāo)題和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為頁面內(nèi)鏈接,不會(huì)跳轉(zhuǎn)到其他頁面
# 所以不需要保存
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)
代碼中定義了兩個(gè)全局變量來保存信息。章節(jié)內(nèi)容保存在chapter_info列表里,里面包含了層級(jí)結(jié)構(gòu),大致結(jié)構(gòu)為:
[
{
'title': 'first_level_chapter',
'url': 'www.xxxxxx.com',
'child_chapters': [
{
'title': 'second_level_chapter',
'url': 'www.xxxxxx.com',
}
...
]
}
...
]
3.3 獲取章節(jié)內(nèi)容
還是同樣的方法定位章節(jié)內(nèi)容:
05.獲取章節(jié)內(nèi)容
代碼中我們通過itemprop這個(gè)屬性來定位,好在一級(jí)目錄內(nèi)容的元素位置和二級(jí)目錄內(nèi)容的元素位置相同,省去了不少麻煩。
html_template = """
{content}
"""
def get_content(url):
"""
解析URL,獲取需要的html內(nèi)容
:param url: 目標(biāo)網(wǎng)址
: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內(nèi)容
: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']
# 文件夾不存在則創(chuàng)建(多級(jí)目錄)
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
經(jīng)過上一步,所有章節(jié)的pdf都保存下來了,最后我們希望留一個(gè)pdf,就需要合并所有pdf并刪除單個(gè)章節(jié)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:
# 先合并一級(jí)目錄的內(nèi)容
first_level_title = pdf['title']
總結(jié)
以上是生活随笔為你收集整理的python爬虫爬取pdf_Python 爬虫:爬取教程生成 PDF的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为充电的效果_华为充电特效主题插件下载
- 下一篇: python开发温湿度显示界面_用Mic