实战1-python爬取安全客新闻

一般步骤:确定网站--搭建关系--发送请求--接受响应--筛选数据--保存本地

1.拿到网站首先要查看我们要爬取的目录是否被允许

一般网站都会议/robots.txt目录,告诉你哪些地址可爬,哪些不可爬,以安全客为例子

2. 首先测试在不登录的情况下是否请求成功

可见,该请求成功;有很多网站在没有登录的情况下是请求失败的,这时需要添加请求头信息,

注意:有的cookie 会根据时间戳生成,有的会失效

haders={},

2.1、首先 F12 到 Network 下,F5刷新 ,复制 Requests Headers然后把它转换成 json 格式

2.1.1 Requests Headers 转 json 格式有很多种方法

  1. 在线转 json 格式的网站:在线HTTP请求/响应头转JSON工具 - UU在线工具

2.如果电脑没网 在终端下载:pip install feapder

feapder create -j

req=requests.get(url=url).text 是把所有的文本都提取出来,会很乱,所有我们需要筛选,整理一下

可以发现,我们需要的数据在 a 标签中

<a target="_blank" href="/post/id/291754">苹果委托进行数据泄露研究,以强调端到端加密的必要性</a>

数据多了id位数也可能会增加;也可以把id写死,根据291754是个六位数,所以 \d{6}只匹配 id是六位数的。

python 复制代码
Title=re.findall(r'<a target="_blank" href="/post/id/\d+">(.*?)</a>',req)

\d+

注意代码格式

range() 取值 [ )

最终代码:

python 复制代码
import re
import requests
#headers={}
url='https://www.anquanke.com/'
req=requests.get(url=url).text
# print(req)
dict={}
for i in range(1,20):
    dict['Title']=re.findall(r'<a target="_blank" href="/post/id/\d+">(.*?)</a>',req)[i]
    dict['url']=re.findall(r'<a target="_blank" href="(/post/id/\d+)">',req)[i]
    print(dict)

优化后的代码:

python 复制代码
import re
import requests
url='https://www.anquanke.com/'
req=requests.get(url=url)
print(req.status_code)
req=req.text
dict={}
Title=re.findall(r'<a target="_blank" href="(/post/id/\d+)">(.*?)</a>',req)
# print(Title)
for title in Title:
    dict['Title']=title[1]
    dict['url']=url+title[0]
    print(dict)
相关推荐
zone773921 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant21 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来1 天前
在node项目中执行python脚本
前端·python·node.js
IVEN_1 天前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend1 天前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽1 天前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_2 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮2 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling2 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python