requests模块:python中原生的一款基于网络请求的模块,功能非常强大,简单便捷,效率极高。
作用:模拟浏览器发请求。
如何使用:(requests模块的编码流程)
- 指定URL
- 发起请求
- 获取响应数据
- 持久化存储
环境安装: - pip install requests
实战编码:
- 需求:爬取搜狗首页的页面数据
import requests
# step1:指定url
url='https://www.sogou.com'
# step2:发起请求
# get方法会返回一个响应对象
response = requests.get(url=url)
# step3:获取响应数据.text返回的是字符串形式的响应数据
page_text = response.text
print(page_text)
# step4:持久化存储
with open('./sougou.html','w',encoding='utf-8')as fp:
fp.write(page_text)
print('爬取数据结束!!!')
`