requests模块:python中原生的一款基于网络请求的模块
作用:模拟浏览器发送请求
如何使用(requests模块的编码流程):
- 指定url
- 发起请求
- 获取相应数据
- 持久化存储
安装:
pip install requests
爬取搜狗首页的数据:
import requests
# 1.指定url
url = 'https://www.sogou.com/'
# 2.发起请求
# get方法会返回一个相应对象
response = requests.get(url=url)
# 3.获取相应数据,text返回的是字符串形式的数据
page_text = response.text
print(page_text)
# 4.持久化存储
with open('./sougou.html', 'w', encoding='utf-8') as fp:
fp.write(page_text)
print('数据爬取结束')
爬取后页面: