day16-html和requests
1.requests的基本用法
文本用text,js文件用json,图片,视频,音频等用content.
a.爬网络数据
# 1. 对网页发送请求获取数据
response = requests.get('https://cd.zu.ke.com/zufang')
# 2. 设置文本内容的编码方式(如果打印结果乱码就需要设置成和网页编码方式一样的值)
response.encoding = 'utf-8'
# 3. 获取网页内容(获取网页源代码)
result = response.text
print(result)
b.请求接口数据
# 1.对接口发送请求
response = requests.get('https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js')
# 2)对请求结果进行json解析(json解析就是将json数据转换成对应的Python数据)
result = response.json()
for x in result['hero']:
print(x['name'], x['goldPrice'])
c.下载图片、视频、音频等
# 1. 对图片地址、视频地址或者音频地址发送请求
response = requests.get('https://img12.360buyimg.com/babel/s1580x830_jfs/t1/99442/1/34931/62347/63ae7b9eFf6b0a7c4/ff41e7e9b60d34b4.jpg!cc_1580x830.webp')
# 2. 获取请求结果(视频、音频或者图片的数据)
result = response.content
# 3. 将图片、视频或者图片的数据保存到文件中
with open('files/a.png', 'wb') as f:
f.write(result)
2.json数据
json支持的数据类型格式:
1.数字 - 和数学一样
2.字符串 - 只能使用双引号
3.布尔 - true、false
4.空值 - null
5.数组(列表) - [数据1, 数据2, 数据3]
6.字典 - {键1: 值1, 键2: 值2, …} (字典的键只能是字符串,值可以是任何类型的数据)
Python与json的相互转换
json转python:使用json.loads()将括号中json数据转化为python数据
python转json:使用json.loads()将括号中python数据转化为json数据
3.案例:下载英雄选择音频
import requests
response = requests.get('https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js')
result = response.json()
for x in result['hero']:
f = open(f"./file/{x['name']}.ogg", 'wb')
video = requests.get(f"{x['selectAudio']}")
f.write(video.content)
f.close()
4.浏览器反爬
a.对网页发送请求(先伪装成浏览器)
headers = {
'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)
b.获取网页内容
print(response.text)