Python爬虫简单实现CSDN博客文章标题列表
操作步骤:
- 分析接口,怎么获取数据?
- 模拟接口,尝试提取数据
- 封装接口函数,实现函数调用。
1.分析接口
打开Chrome
浏览器,开启开发者工具(F12快捷键)。
在浏览器中输入CSDN网址 : https://blog.csdn.net
,看``
根据分析,提取到了AJAX调用接口如下:
curl 'https://blog.csdn.net/api/articles?type=new&category=home' -H 'authority: blog.csdn.net' -H 'pragma: no-cache' -H 'cache-control: no-cache' -H 'accept: application/json, text/javascript, */*; q=0.01' -H 'dnt: 1' -H 'x-requested-with: XMLHttpRequest' -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36' -H 'x-tingyun-id: im-pGljNfnc;r=1231324324' -H 'sec-fetch-site: same-origin' -H 'sec-fetch-mode: cors' -H 'sec-fetch-dest: empty' -H 'referer: https://blog.csdn.net/' -H 'accept-language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,zh-TW;q=0.5' -H $'cookie: uuid_tt_dd=10_293732321.........' --compressed
我们接下来我们开始模拟这个AJAX请求。
"""
说明: 定义了`requests`请求方法`get_resp`用于模拟发送HTTP协议的`GET`请求。
其中可以选择使用代理,如果不是用就甚至`proxies=""`即可。
请求头`headers`需要根据我们分析的请求头选择性填充。
"""
import requests
from lxml import etree
import json
ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
default_socks = 'socks5://127.0.0.1:1084'
def get_resp(url, proxies=default_socks, headers=None, timeout=10):
"""
发送requests请求模块,最多尝试3次
"""
headers = headers
if headers is None:
headers = {'user-agent': ua}
if isinstance(proxies, str):
proxies = {
'http': proxies,
'https': proxies,
}
for _ in range(3):
try:
resp = requests.get(url, proxies=proxies, headers=headers, timeout=timeout)
return resp
except Exception as e:
print(e)
return None
2.模拟接口,尝试提取数据
接下来我们开始模拟接口调用,最终尝试headers
需要携带如下面的信息即可请求成功。
headers = {
'authority': 'blog.csdn.net',
'accept': 'application/json, text/javascript, */*; q=0.01',
'referer': 'https://blog.csdn.net/',
'user-agent': ua,
'x-tingyun-id': 'im-pGljNfnc;r=318932708',
'cookie': 'uuid_tt_dd=10_23458360190-1600318910542-823210; dc_session_id=10_1600318910542.883906; dc_sid=182c9fe1bfb457f42ff2bbd06e456f43; TY_SESSION_ID=f594894c-a5ae-49f0-a95f-bf28e848294d; c_first_ref=default; c_first_page=https%3A//blog.csdn.net/; announcement=%257B%2522isLogin%2522%253Afalse%252C%2522announcementUrl%2522%253A%2522https%253A%252F%252Flive.csdn.net%252Froom%252Fyzkskaka%252F5n5O4pRs%253Futm_source%253D1598583200%2522%252C%2522announcementCount%2522%253A0%252C%2522announcementExpire%2522%253A3600000%257D; c-login-auto=1; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1600318916; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1600318916; Hm_up_6bcd52f51e9b3dce32bec4a3997715ac=%7B%22islogin%22%3A%7B%22value%22%3A%220%22%2C%22scope%22%3A1%7D%2C%22isonline%22%3A%7B%22value%22%3A%220%22%2C%22scope%22%3A1%7D%2C%22isvip%22%3A%7B%22value%22%3A%220%22%2C%22scope%22%3A1%7D%7D; Hm_ct_6bcd52f51e9b3dce32bec4a3997715ac=6525*1*10_23458360190-1600318910542-823210; dc_tos=qgsdzo',
}
url = 'https://blog.csdn.net/api/articles?type=more&category=python&shown_offset=1600319325563840'
resp = get_resp(url, headers=headers)
print(resp.status_code, url)
jdata = resp.json()
执行结果:
200 https://blog.csdn.net/api/articles?type=more&category=python&shown_offset=1600319325563840
articles = jdata['articles']
offset = jdata['shown_offset']
title_list = [i['title'] for i in articles]
print('offset:', offset)
print('title_list:', title_list)
执行结果:
offset: 0
title_list: ['Windows 环境下 PyCharm 配置 PyQt5 图形化 QT Designer', 'Python将网页转化为PDF(python网页自动长截图)', 'LeetCode 126. 单词接龙 II python', 'python爬虫之爬取多篇含有关键词的文章标题和内容优化', 'Python利用Groupby机制绘制柱状图时KeyError和TypeError问题及解决方法', '算法练习-KNN分类预测', 'win10 python3 安装 Tensorflow-gpu 问题及解决', 'Python爬取高质量电脑壁纸,还是很好看的', 'Tutorial教程:mxnet模型转换为tensorflow 2.0/keras 模型-全网唯一', 'pytorch线性回归代码实现 测试,保存,加载模型 有详细注释']
上面已经模拟成功接口调用,接下来我们实现函数化
3. 接口封装函数化
接口模拟调用成功后,我们开始将变量参数提取出来,作为函数的参数,实现函数化。
我们简单封装了提取页数参数的fetch_page
函数,使用如下
fetch_page(5)
这样我们可以根据调度频率来决定每次提取的页面数量。
def fetch_page(pn=10):
headers = {
'authority': 'blog.csdn.net',
'accept': 'application/json, text/javascript, */*; q=0.01',
'referer': 'https://blog.csdn.net/',
'user-agent': ua,
'x-tingyun-id': 'im-pGljNfnc;r=318932708',
'cookie': 'uuid_tt_dd=10_23458360190-1600318910542-823210; dc_session_id=10_1600318910542.883906; dc_sid=182c9fe1bfb457f42ff2bbd06e456f43; TY_SESSION_ID=f594894c-a5ae-49f0-a95f-bf28e848294d; c_first_ref=default; c_first_page=https%3A//blog.csdn.net/; announcement=%257B%2522isLogin%2522%253Afalse%252C%2522announcementUrl%2522%253A%2522https%253A%252F%252Flive.csdn.net%252Froom%252Fyzkskaka%252F5n5O4pRs%253Futm_source%253D1598583200%2522%252C%2522announcementCount%2522%253A0%252C%2522announcementExpire%2522%253A3600000%257D; c-login-auto=1; Hm_lvt_6bcd52f51e9b3dce32bec4a3997715ac=1600318916; Hm_lpvt_6bcd52f51e9b3dce32bec4a3997715ac=1600318916; Hm_up_6bcd52f51e9b3dce32bec4a3997715ac=%7B%22islogin%22%3A%7B%22value%22%3A%220%22%2C%22scope%22%3A1%7D%2C%22isonline%22%3A%7B%22value%22%3A%220%22%2C%22scope%22%3A1%7D%2C%22isvip%22%3A%7B%22value%22%3A%220%22%2C%22scope%22%3A1%7D%7D; Hm_ct_6bcd52f51e9b3dce32bec4a3997715ac=6525*1*10_23458360190-1600318910542-823210; dc_tos=qgsdzo',
}
offset='1600319325563840'
for _ in range(pn):
url = f'https://blog.csdn.net/api/articles?type=more&category=python&shown_offset={offset}'
resp = get_resp(url, headers=headers)
print(resp.status_code, url)
jdata = resp.json()
articles = jdata['articles']
offset = jdata['shown_offset']
for i in articles:
print(i['title'])
fetch_page(3)
执行结果:
SOCKSHTTPSConnectionPool(host='blog.csdn.net', port=443): Read timed out. (read timeout=10)
200 https://blog.csdn.net/api/articles?type=more&category=python&shown_offset=1600319325563840
[PyQt5]python点击按钮实现窗口切换
Anaconda 如何切换Python版本 + Pycharm的设置
【PPD12】直方图
kotlin中join方法效果验证
9.16任务:条件语句,循环语句,range函数,enumerate函数,推导式
python金融正太var方差-协方差代码
python爬取阳光问政
openpyxl模块基本用法
Python:__init__()方法
Pandas用法详细介绍
200 https://blog.csdn.net/api/articles?type=more&category=python&shown_offset=0
语义分割制作自己的voc数据集
Python继承小案例
Pycharm如何创建项目
两个链表的第一个公共节点---遍历彼此的节点
LeetCode刷题(163)~每日温度【单调栈】
Python-纯字母字符串内存地址一样,否则不一样,如下案例
OpenCV笔记02
Python编程:从入门到实践第六章读书笔记6.2使用字典
TensorFlow 19——ch14-词的向量表示:word2vec与词嵌入
笔记_005_布尔值_比较运算符_逻辑运算符_同一运算符
200 https://blog.csdn.net/api/articles?type=more&category=python&shown_offset=0
Selenium安装与基本使用
【剑指offer】#05替换空格 - 正则 - 数组 - 双指针
Python中‘r‘,‘r+‘,‘w‘,‘w+‘,‘a‘,‘a+‘区别总结
2020CISCN初赛-crypto-lfsr writeup
读取txt文件后修改特定内容并保存
Pycharm中文指南
python切片操作的注意事项
2020-09-16
LeetCode226:翻转二叉树
练习:二元逻辑回归实现
总结
这里使用的时requests
库模拟发送GET
请求,其中的cookies
信息是手工填写的,当然也可以稍微复杂一点的实现自动获取,这里只是介绍基础提取方法。
向了解更多知识可以访问 虫师de江湖 全面了解更多关于爬虫知识。