为了学习网络爬虫,我爬取了网络爬虫届大佬崔庆才的所有Python博客,并转换成了pdf,以便后续学习。
1.代码思路
- 获取所有博客的URL
- 获得每篇博客的html内容,并转化为pdf文件
- 合并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(