【Python如何使用requests+re库进行简单爬虫实例应用】

1、安装requests库

(1)直接win+R输入cmd进入命令行界面,执行命令:pip install requests

(2)再Pycharm中,'File'-'Settings'-'Python interpreter'-'+'-搜索'requests'-'install package'下载,如下图所示

2、实例:爬虫提取百度热搜的前十条,并写入一个文件中。代码如下:

python 复制代码
import requests
import re  # 导入库
url = "https://top.baidu.com/board?platform=pc&sa=pcindex_entry"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWeb"
                         "Kit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"}  # 创建变量
response = requests.get(url, headers=headers).text  # 发送get请求
most_searched_hashtags = re.findall(r',"indexUrl":"","query":"(.*?)","rawUrl"', response)  # 正则表达式提取内容成一个列表
with open(r'D:\pythonn\pythonProject\240202package\hot1.txt', mode='a+', encoding='utf-8') as file:  # 创建一个文件hot1.txt,打开文件追加内容
    for i in range(10):  # 循环10次
        print("热搜榜第{}:{}".format(i, most_searched_hashtags[i]))  # 输出前10条热搜内容
        file.write("热搜榜第{}:{}\n".format(i, most_searched_hashtags[i]))  # 将输出热搜内容追加写入hot1.txt文件中

若要更细了解requests,re库和文件读写操作可以借鉴: 【Pyhton中requests库、re库、文件读写的了解】-CSDN博客

3、输出结果如下:

相关推荐
M--Y9 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
岁月宁静10 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
LiaoWL12310 小时前
NumPy 入门实战(二):向量化与余弦相似度——从 ndarray 到 Embedding
python·numpy·embedding
forest_0910 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
databook14 小时前
时间序列数据,先拆规律还是先查异常
python·数据挖掘·数据分析
师夷长技以自愈14 小时前
手搓 AI Agent 第 8 篇:从手写循环到画流程图——LangGraph 封装
人工智能·python
aifannihao15 小时前
Rust 1.100 的 DropGuard:用 Python 实测失败回滚与吞异常
python·rust·异常处理·标准库·contextlib
用户0190275816117 小时前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
wuyk55517 小时前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
2601_9679791218 小时前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt