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

相关推荐
weixin199701080166 分钟前
[特殊字符] 从1688接口设计,学习高可用API的最佳实践(附Python源码)
python·学习·spring
隔壁大炮12 分钟前
MNE-Python 第8天学习笔记:时频分析(ERD/ERS)
python·eeg·mne·脑电数据处理
小许同学记录成长19 分钟前
gr-analog 模拟信号模块完整源码分析
python·算法·信号处理
MediaTea28 分钟前
PyTorch:主要模块简介
人工智能·pytorch·python·深度学习·机器学习
技术小猪猪30 分钟前
PromptOps:用Python构建生产级提示词工程体系
人工智能·python·ai·自动化·prompt
工业互联网专业1 小时前
国潮男装微博评论数据分析系统的设计与实现 _flask+spider
python·flask·毕业设计·源码·课程设计·spider
BUG研究员_1 小时前
python之数据分析-pandas部分
python·信息可视化·数据分析
覆东流1 小时前
Python变量与数值类型
开发语言·后端·python
Cthy_hy1 小时前
Python 算法竞赛:快速IO+字符串常用方法一站式整理
开发语言·python·算法
技术钱1 小时前
字符分割器组件的使用
android·python