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

相关推荐
站大爷IP35 分钟前
Python实现Excel数据自动化处理:从繁琐操作到智能流程的蜕变
python
BBB努力学习程序设计39 分钟前
Python 进阶知识点精讲:上下文管理器(Context Manager)的原理与实战
python·pycharm
清水白石00841 分钟前
《深入 super() 的世界:MRO 与 C3 线性化算法的全景解析与实战指南》
python
大厂技术总监下海42 分钟前
Python 开发者的“新引擎”:Rust 编写的解释器,性能与安全兼得
python·开源
Swizard1 小时前
别再硬编码配置了!5分钟带你用 PyYAML 让 Python 项目“活”起来
python
love530love2 小时前
Windows 下 Z-Image-Turbo 专业版 Gradio 生成器实战:功能增强全记录
人工智能·windows·python·大模型·gradio·博客之星·z-image
人工干智能2 小时前
Chat Completions API中的三种role:“system“,“user“,“assistant“
python·llm
Darenm1112 小时前
JWT鉴权的实现:从原理到 Django + Vue3
后端·python·django
Funny_AI_LAB2 小时前
Zcode:智谱AI推出的轻量级 AI IDE 编程利器
人工智能·python·算法·编辑器
2501_944452232 小时前
活动记录 Cordova 与 OpenHarmony 混合开发实战
python