利用Python爬取教程并转为PDF文档!(1)

使用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 = “”"

<meta charset="UTF-8">

{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。

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']
    dir_name = os.path.join(os.path.dirname(
        __file__), 'gen', first_level_title)
    padf_path = os.path.join(dir_name, first_level_title + '.pdf')
    pdf_input = PdfFileReader(open(padf_path, 'rb'))
    # 获取 pdf 共用多少页
    page_count = pdf_input.getNumPages()
    for i in range(page_count):
        pdf_output.addPage(pdf_input.getPage(i))
    # 添加书签
    parent_bookmark = pdf_output.addBookmark(
        first_level_title, pagenum=pagenum)
    # 页数增加
    pagenum += page_count
    # 存在子章节
    if pdf['child_chapters']:
        for child in pdf['child_chapters']:
            second_level_title = child['title']
            padf_path = os.path.join(dir_name, second_level_title + '.pdf')
            pdf_input = PdfFileReader(open(padf_path, 'rb'))

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)

mg-3eu479yL-1713761604558)]

[外链图片转存中…(img-3hyII0b9-1713761604558)]

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值