当前位置:   article > 正文

利用Python爬取教程并转为PDF文档!_python wkhtmltopdf

python wkhtmltopdf

2.1 软件安装


由于我们是要把html转为pdf,所以需要手动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

2.2 库安装


  • pip install requests # 用于网络请求
  • pip install beautifulsoup4 # 用于操作html
  • pip install pdfkit # wkhtmltopdf 的Python封装包
  • pip install PyPDF2 # 用于合并pdf

3、爬取内容


本文的目标网址为:http://python3-cookbook.readthedocs.io/zh_CN/latest/ 。

3.1 获取教程名称


页面的左边一栏为目录,按F12调出开发者工具并按以下步骤定位到目录元素:

① 点击开发者工具左上角"选取页面元素"按钮;

② 用鼠标点击左上角教程名称处。

通过以上步骤即可定位到目录元素,用图说明:

image

从图看到我们需要的教程名称包含在<div class="wy-side-nav-search"></div>之间的a标签里。假设我们已经获取到了网页内容为html,可以使用以下代码获取该内容:

book_name = soup.find(‘div’, class_=‘wy-side-nav-search’).a.text

3.2 获取目录及对应网址


使用与 2.1 相同的步骤来获取:

image

从图看到我们需要的目录包含在<div class="section"></div>之间,<li class="toctree-l1"></li>标签里为一级目录及网址;<li class="toctree-l2"></li>标签里为二级目录及网址。当然这个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):

"""
  • 1
解析全部章节的标题和url
  • 1
:param html: 需要解析的网页内容
  • 1
:return None
  • 1
"""
  • 1
soup = BeautifulSoup(html, 'html.parser')
  • 1
# 获取书名
  • 1
book_name = soup.find('div', class_='wy-side-nav-search').a.text
  • 1
menu = soup.find_all('div', class_='section')
  • 1
chapters = menu[0].div.ul.find_all('li', class_='toctree-l1')
  • 1
for chapter in chapters:
  • 1
    info = {}
  • 1
    # 获取一级标题和url
  • 1
    # 标题中含有'/'和'*'会保存失败
  • 1
    info['title'] = chapter.a.text.replace('/', '').replace('*', '')
  • 1
    info['url'] = base_url + chapter.a.get('href')
  • 1
    info['child_chapters'] = []
  • 1
    # 获取二级标题和url
  • 1
    if chapter.ul is not None:
  • 1
        child_chapters = chapter.ul.find_all('li')
  • 1
        for child in child_chapters:
  • 1
            url = child.a.get('href')
  • 1
            # 如果在url中存在'#',则此url为页面内链接,不会跳转到其他页面
  • 1
            # 所以不需要保存
  • 1
            if '#' not in url:
  • 1
                info['child_chapters'].append({
  • 1
                    'title': child.a.text.replace('/', '').replace('*', ''),
  • 1
                    'url': base_url + child.a.get('href'),
  • 1
                })
  • 1
    chapter_info.append(info)
  • 1

代码中定义了两个全局变量来保存信息。章节内容保存在chapter_info列表里,里面包含了层级结构,大致结构为:

[

{
  • 1
    'title': 'first_level_chapter',
  • 1
    'url': 'www.xxxxxx.com',
  • 1
    'child_chapters': [
  • 1
        {
  • 1
            'title': 'second_level_chapter',
  • 1
            'url': 'www.xxxxxx.com',
  • 1
        }
  • 1
        ...            
  • 1
    ]
  • 1
}
  • 1
...
  • 1

]

3.3 获取章节内容

还是同样的方法定位章节内容:

05.获取章节内容

代码中我们通过itemprop这个属性来定位,好在一级目录内容的元素位置和二级目录内容的元素位置相同,省去了不少麻烦。

html_template = “”"

<meta charset="UTF-8">
  • 1

{content}

“”"

def get_content(url):

"""
  • 1
解析URL,获取需要的html内容
  • 1
:param url: 目标网址
  • 1
:return: html
  • 1
"""
  • 1
html = get_one_page(url)
  • 1
soup = BeautifulSoup(html, 'html.parser')
  • 1
content = soup.find('div', attrs={'itemprop': 'articleBody'})
  • 1
html = html_template.format(content=content)
  • 1
return html
  • 1

3.4 保存pdf


def save_pdf(html, filename):

"""
  • 1
把所有html文件保存到pdf文件
  • 1
:param html:  html内容
  • 1
:param file_name: pdf文件名
  • 1
:return:
  • 1
"""
  • 1
options = {
  • 1
    'page-size': 'Letter',
  • 1
    'margin-top': '0.75in',
  • 1
    'margin-right': '0.75in',
  • 1
    'margin-bottom': '0.75in',
  • 1
    'margin-left': '0.75in',
  • 1
    'encoding': "UTF-8",
  • 1
    'custom-header': [
  • 1
        ('Accept-Encoding', 'gzip')
  • 1
    ],
  • 1
    'cookie': [
  • 1
        ('cookie-name1', 'cookie-value1'),
  • 1
        ('cookie-name2', 'cookie-value2'),
  • 1
    ],
  • 1
    'outline-depth': 10,
  • 1
}
  • 1
pdfkit.from_string(html, filename, options=options)
  • 1

def parse_html_to_pdf():

"""
  • 1
解析URL,获取html,保存成pdf文件
  • 1
:return: None
  • 1
"""
  • 1
try:
  • 1
    for chapter in chapter_info:
  • 1
        ctitle = chapter['title']
  • 1
        url = chapter['url']
  • 1
        # 文件夹不存在则创建(多级目录)
  • 1
        dir_name = os.path.join(os.path.dirname(__file__), 'gen', ctitle)
  • 1
        if not os.path.exists(dir_name):
  • 1
            os.makedirs(dir_name)
  • 1
        html = get_content(url)
  • 1
        padf_path = os.path.join(dir_name, ctitle + '.pdf')
  • 1
        save_pdf(html, os.path.join(dir_name, ctitle + '.pdf'))
  • 1
        children = chapter['child_chapters']
  • 1
        if children:
  • 1
            for child in children:
  • 1

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

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

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

img

img

img

img

img

img

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

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

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

img-kG81JVhn-1713005237072)]

[外链图片转存中…(img-pOiN2fBA-1713005237073)]

img

img

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

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

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

img
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/862098
推荐阅读
相关标签
  

闽ICP备14008679号