【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、输出结果如下:

相关推荐
皮卡丘不断更1 分钟前
手搓本地 RAG:我用 Python 和 Spring Boot 给 AI 装上了“实时代码监控”
人工智能·spring boot·python·ai编程
爱打代码的小林17 分钟前
基于 MediaPipe 实现实时面部关键点检测
python·opencv·计算机视觉
NPE~35 分钟前
自动化工具Drissonpage 保姆级教程(含xpath语法)
运维·后端·爬虫·自动化·网络爬虫·xpath·浏览器自动化
极客小云35 分钟前
【ComfyUI API 自动化利器:comfyui_xy Python 库使用详解】
网络·python·自动化·comfyui
闲人编程1 小时前
Elasticsearch搜索引擎集成指南
python·elasticsearch·搜索引擎·jenkins·索引·副本·分片
痴儿哈哈1 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
花酒锄作田1 小时前
SQLAlchemy中使用UPSERT
python·sqlalchemy
SoleMotive.1 小时前
一个准程序员的健身日志:用算法调试我的增肌计划
python·程序员·健身·职业转型
亓才孓1 小时前
[Properties]写配置文件前,必须初始化Properties(引用变量没执行有效对象,调用方法会报空指针错误)
开发语言·python
Bruk.Liu1 小时前
(LangChain 实战14):基于 ChatMessageHistory 自定义实现对话记忆功能
人工智能·python·langchain·agent