requests笔记
发送get请求:
发送get请求,直接’requests.get’
‘’’
python
response= request.get(“https://www.baidu.com/”)
‘’’
response的一些属性:
‘’’
python
import requests
kw = {‘wd’:‘中国’}
headers={‘User-Agent’:‘浏览的信息’}
params
接受一个字典或者字符串的查询参数,字典类型自动转化为url编码,不需要urlencode()
response = requests.get(“http://www.baidu.com/s”,params=kw,headers = headers)
查看相应内容,response.text,返回Unicode格式的数据
print(response.text)
#相应内容为字节流数据 response.content
print(response.content)
查看url地址
print(response.url)
查看响应头部字符编码
print(response.status_code)
response.text和response.content的区别:
1、response.content:这个是直接从网络上抓取下来的数据,没有经过解码,是一个bytes类型。其实硬盘和网络上传输的数据都是bytes
2、response.text:这是str(字符串)类型的数据,这是requests根据自己的猜测进行解码的方式,可能会出现乱码情况。这是应该使用response.content.decode('utf-8')
进行手动解码。
post请求:
直接调用requests.post
j就可以了
若返回的数据是json数据,可以调用respons.json()
来将json字符串转换为字典或者列表。
以拉勾网为例:
import requests
headers={
'User-Agent':'写成自己的'}
data={
'first':'true',
'pn':'1',
'kd':'python'}
response = requests.post('https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false',data=data,headers=headers)
print(response.json())
若返回结果是你的操作过于频繁,请稍后访问。
写成headers={ 'Referer':'https://www.lagou.com/jobs/list_python/p-city_0?&cl=false&fromSearch=true&labelWords=&suginput=sec-fetch-dest: empty', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'}
应该就可以了。
处理cookie:
如果想要在多次请求中使用cookie,应该使用session/Session。不去分辨大小写
#python
import requests
url= "http://www.renren.com/Plogin.do"
data = {"email":"账号信息","password":"密码"}
headers={"User-Agent":"填写为自己的"}
session=requests.Session()
session.post(url,data,headers= headers)
response= session.get("http://www.renren.com/880151247/profile")
with open('renren.html','w',encoding= 'utf-8') as fp:
fp.write(response.text)
IP代理:
在请求方法中(比如get或post)传递proxies参数就可以
#python
import requests
url = "http://httpbin.org/get"
headers={"User-Agent":""}
proxy={'http':'125.108.106.107:9000'}#在代理网站获取到的ip
resp = requests.get(url,headers = headers,proxies=proxy)
print(resp.read().decode('utf-8'))
常见代理:
西刺免费代理ip:https://www.xicidaili.com/nn/
快代理:https://www.kuaidaili.com/?utm_source=bdtg&utm_campaign=a10a1&utm_medium=a10