Python爬虫:requests模块使用

requests模块

python中原生的一款基于网络请求的模块,功能非常强大,简单便捷,效率极高。用于发送请求,模拟浏览器上网。

使用流程

  1. 指定url
  2. 发起请求
  3. 获取响应数据
  4. 持久化存储

环境安装

建议直接下载Anaconda,在PyCharm中使用Anaconda的默认环境,其中就包含了requests模块。
在这里插入图片描述

爬虫的第一个实例:获取搜狗搜索网页的源代码

# 获取搜狗首页的数据

import requests

# 指定url
sougouURL = 'https://www.sogou.com/'

# 发起请求
# requests.get()返回一个相应对象
response = requests.get(url=sougouURL)

# 获取响应数据
# text返回字符串类型数据
# 这里会得到该页面的html源码
pageText = response.text
print(pageText)

# 存储获取到的数据
with open('./sougou.html','w') as fp:
    fp.write(pageText)

print('爬取数据结束')

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Dae_Lzh/article/details/118786755