本篇文章流程(爬虫基本思路):
一. 数据来源分析 (只有当你找到数据来源的时候, 才能通过代码实现)
- 确定需求(要爬取的内容是什么?)
爬取文章内容 保存pdf - 通过开发者工具进行抓包分析 分析数据从哪里来的?
Python从零基础入门到实战系统教程、源码、视频,想要数据集的同学也可以点这里
二. 代码实现过程
- 发送请求 对于文章列表页面发送请求
- 获取数据 获取网页源代码
- 解析数据 文章的url 以及 文章标题
- 发送请求 对于文章详情页url地址发送请求
- 获取数据 获取网页源代码
- 解析数据 提取文章标题 / 文章内容
- 保存数据 把文章内容保存成html文件
- 把html文件转成pdf文件
- 多页爬取
导入模块
import requests
import parsel
import os
import re
import pdfkit
创建文件夹
filename = 'pdf\\'
filename_1 = 'html\\'
if not os.path.exists(filename):
os.mkdir(filename)
if not os.path.exists(filename_1):
os.mkdir(filename_1)
发送请求
for page in range(1, 11):
print(f'=================正在爬取第{page}页数据内容=================')
url = f'https://blog.***.net/qdPython/article/list/{page}'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
数据解析
selector = parsel.Selector(response.text)
href = selector.css('.article-list a::attr(href)').getall()
如果把列表里面每一个元素 都提取出来
for index in href:
response_1 = requests.get(url=index, headers=headers)
selector_1 = parsel.Selector(response_1.text)
title = selector_1.css('#articleContentId::text').get()
new_title = change_title(title)
content_views = selector_1.css('#content_views').get()
html_content = html_str.format(article=content_views)
html_path = filename_1 + new_title + '.html'
pdf_path = filename + new_title + '.pdf'
with open(html_path, mode='w', encoding='utf-8') as f:
f.write(html_content)
print('正在保存: ', title)
替换特殊字符
def change_title(name):
mode = re.compile(r'[\\\/\:\*\?\"\<\>\|]')
new_name = re.sub(mode, '_', name)
return new_name
运行代码,即可下载HTML文件

转换成PDF文件
config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
pdfkit.from_file(html_path, pdf_path, configuration=config)
