requests知识点(1)

一、下载 requests 模块:

pip install requests

二、基本使用流程

import requests

# 1.定制url,既即将访问的url
url = ‘www.sogou.com’
# 2.UA 伪装,既模拟浏览器访问 url ,可以去network中查找 user-agent后的内容就是。(定制请求头)
headers = {
	'User-Agent':'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0'
}
# 3.也可以给url中携带参数,讲参数保存到字典中
params = {
	‘name’:'lihaha'
}
# 4.既可以发送请求,response接响应数据
response=requsts.get(url=url,params=params,headers=headers)
# 5.响应数据持久化处理
with open('./so','w',encodig='utf-8') as f:
	f.write(response.text)
post 请求
response = requests.post(url=url,data=params,headers=headers)

三、response 属性

属性描述
response.textstr形式的响应数据(网页源码)
response.contentbytes类型的响应数据
response.status_code响应的状态码
response.headers响应头信息
response.request获取响应对应的请求
response.encoding当前的字符编码
response.encoding = ‘utf-8’设置字符编码
response.json()request 内置的json解码器,前提是提前知道返回的是json数据,否则报错

四、代理

# 使用代理ip是一种非常必要的反反爬的一种方式

proxies = {
    "http": "https://175.44.148.176:9000",
    "https": "https://183.129.207.86:14002"
}
response = requests.get(url=url, proxies=proxies)

# 如果代理需要用户名和密码
proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}

五、解码

有时候html页面的编码格式与python默认的utf-8解码格式不同
# 让python解码适应html源码格式
response = requests.get('https://www.csdn.net/')
response.encoding = response.apparent_encoding
print(response.text)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值