Day1爬虫
request
python环境
- 系统环境:通过安装python得到的
- 虚拟环境:由程序员创建的,(可以创建多个,创建的前提是系统环境存在)
- 创建虚拟环境的建议:
- 学习的时候:一类项目一个虚拟环境(爬虫的虚拟环境、数据分析的虚拟环境….)
- 实际工作、做项目:一个项目一个虚拟环境
request的基本用法
-
请求网络数据:requests.get(请求地址)
import requests response = requests.get('https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js')
-
设置解码方式(乱码的是需要设置的 - 一定要在获取结果之前设置)
response.encoding='utf-8'
-
获取请求结果
# 1)获取请求结果对应的文本数据 - 用于爬网页 print(response.text) # 2)获取二进制格式的请求结果 - 下载图片、视频、音频 print(response.content) # 3)获取请求结果json转换的结果 - json接口 print(response.json())
添加请求头
- 请求发送
-
添加header:a.浏览器伪装(user-agent)、b.免密登录(cookie)、c.设置代理(proxies)
import requests headers = { 'cookie': 'bid=58Gyjz_NAcA; ll="118318"; douban-fav-remind=1; viewed="36164018_36221918"; ap_v=0,6.0', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' } response = requests.get('https://movie.douban.com/top250', headers=headers)
-
获取结果
result=response.text print(result)
下载图片,音频,视频
-
获取网络图片数据
response=requests.get('https://p2.itc.cn/images01/20210120/abc681f6899e4f22bdfb77dd262f7ab7.jpeg') result = response.content print(type(result))
-
保存数据到本地文件
with open('./files/a.jpg','wb') as f:
f.write(result)
- 载音频,下载的音频只能在浏览器中打开
response = requests.get('https://game.gtimg.cn/images/lol/act/img/vo/choose/1.ogg')
result = response.content
with open('./files/b.mp3','wb') as f:
f.write(result)