python学习笔记6

requests库

文件上传

在读取网页时加入参数files

1
2
3
import requests
files = {'file': open('filename', 'rb')} # 只读方式打开,只写为wb
r = requests.post('http://httpbin.org/post', files=files)

cookies

RequestsCookieJar类,可通过cookies.items()获取key和value

1
2
3
4
5
import requests
r = requests.get("https://github.com/")
print(r.cookies)
for key, value in r.cookies.items():
print(key+'='+value)

自定义cookies可以放在headers里

1
2
3
4
5
headers = {
'Cookies': '',
'Host': '',
'User-Agent': '',
}

也可以直接放在cookies里,但需要使用split分割字符串,转换为RequestsCookieJar类

1
2
3
4
5
cookies = ''
jar = requests.cookies.RequestsCookieJar()
for cookie in cookies.split(';'):
key, value = cookie.split('=', 1) # 分隔符/分割次数
r = requests.get('http://www.zhihu.com', cookies=jar, headers=headers)

未完