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

相关推荐
weixin_4193497911 分钟前
Python pdf转换为html
python·pdf
吉小雨21 分钟前
PyTorch经典模型
人工智能·pytorch·python
可愛小吉32 分钟前
Python 课程10-单元测试
开发语言·python·单元测试·tdd·unittest
student.J39 分钟前
傅里叶变换
python·算法·傅里叶
Freak嵌入式1 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
crownyouyou2 小时前
最简单的一文安装Pytorch+CUDA
人工智能·pytorch·python
鸽芷咕2 小时前
【Python报错已解决】libpng warning: iccp: known incorrect sRGB profile
开发语言·python·机器学习·bug
WenGyyyL2 小时前
变脸大师:基于OpenCV与Dlib的人脸换脸技术实现
人工智能·python·opencv
laofashi20152 小时前
AirTest 基本操作范例和参数解释(一)
python·自动化·automation
XyLin.2 小时前
Msf之Python分离免杀
开发语言·python·网络安全·系统安全