Day1-requests基础

Day1-requests基础

1. requests基本用法

import requests

# 1. 请求网络数据: requests.get(请求地址)
response = requests.get('https://cd.zu.ke.com/zufang')
# 2. 设置解码方式(乱码的时候是需要设置的,一定要在获取请求结果之前设置)
response.encoding = 'utf-8'           # 在顶部<head>标签里找<meta>标签的 charset=utf-8 的属性值
# 3. 获取请求结果
# 1) 获取请求结果对应的文本数据  -   爬网页
response = requests.get('https://cd.zu.ke.com/zufang')
print(response.text)

# 2) 获取二进制格式的请求结果   -   下载图片、视频、音频的时候用
response = requests.get('https://img2.baidu.com/it/u=1320841762,1779070643&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1680022800&t=f31623a18b2de3d02d91a0bbf5c57ced')
print(response.content)

# 3) 获取请求结果json转换的结果    -   针对json接口数据 (请求结果得到的数据一般是一个字典)
response = requests.get('https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js')
print(response.json())

2. 添加请求头

# 1. 发送请求
# 添加header: a.浏览器伪装(user-agent)、b.免密登录(cookie)、c.设置代理(proxies)
headers = {
    'cookie': 'bid=3zJOvib4dZM; ap_v=0,6.0; _pk_ses.100001.4cf6=*; __gads=ID=fd8c89f20849e47a-22e45e97c0dc00eb:T=1679904293:RT=1679904293:S=ALNI_MZSmHQWH7--T48pczHe5sACveTTUg; __gpi=UID=00000be207bfa851:T=1679904293:RT=1679904293:S=ALNI_MamdCH7WtxSWoFKiiD2gza7FssGlw; _pk_id.100001.4cf6=8d8f89c6033fa666.1679904277.1.1679904312.1679904277.; __utma=30149280.1762753563.1679904312.1679904312.1679904312.1; __utmb=30149280.0.10.1679904312; __utmc=30149280; __utmz=30149280.1679904312.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=223695111.1733434124.1679904312.1679904312.1679904312.1; __utmb=223695111.0.10.1679904312; __utmc=223695111; __utmz=223695111.1679904312.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
}

response = requests.get('https://movie.douban.com/top250', headers=headers)
# 2. 获取结果
result = response.text
print(result)

3. 下载图片

# 1. 获取网络图片数据
response = requests.get('https://img2.baidu.com/it/u=1320841762,1779070643&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1680022800&t=f31623a18b2de3d02d91a0bbf5c57ced')
result = response.content
print(type(result))         # <class 'bytes'>
# 2. 保存数据到本地文件
with open(r'files\panda.jpg', 'wb') as f:
    f.write(result)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值