为了学爬虫,我用三步爬取了大佬崔庆才爬虫相关文章,并保持为pdf学习

为了学习网络爬虫,我爬取了网络爬虫届大佬崔庆才的所有Python博客,并转换成了pdf,以便后续学习。

1.代码思路

  1. 获取所有博客的URL
  2. 获得每篇博客的html内容,并转化为pdf文件
  3. 合并pdf文件

2.获取所有博客URL

首先,通过崔老师的博客网站可知,目前Python博客内容包含7页,如下图
在这里插入图片描述
通过这些博客分类页面,很方面就能获得每篇博客的网址,代码如下:

#获取所有URL
def get_url():
    url_list = []
    for i in range(7,0,-1):
        if(i==1):
            url = "https://cuiqingcai.com/categories/Python"
        else:
            url = "https://cuiqingcai.com/categories/Python/page/{number}/".format(number=str(i))
        driver.get(url)
        time.sleep(5)
        soup = BeautifulSoup(driver.page_source,'lxml')
        soup = soup.find('div',class_='posts-collapse').find_all('article')
        for a in soup[::-1]:
            url_list.append('https://cuiqingcai.com' + a.find('a',class_='post-title-link')['href'])
    return url_list

3.将每篇博客内容保存为PDF

在将博客内容保存为pdf的过程中,主要使用Python的pdfkit扩展包,pdfkit扩展包能够非常方便的将网页内容或者HTML以及字符串等保存为pdf文件。
pdfkit直接使用pip install pdfkit语句安装即可。
pdfkit扩展包的使用是基于wkhtmltopdf应用程序的,因此在此之前需要先下载安装wkhtmltopdf,安装完成之后需要将其添加的环境变量中,或者在使用pdfkit时以参数的形式指明该程序的路径。
wkhtmltopdf稳定版下载地址:https://wkhtmltopdf.org/downloads.html
将博客内容保存为pdf的具体代码如下:

def html_to_pdf(url_list,html_template,options,config):
    for artical_url in url_list:
        driver.get(
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值