您好,欢迎访问一九零五行业门户网

requests库的基本使用

1. response.content和response.text的区别
response.content是编码后的byte类型(“str”数据类型),response.text是unicode类型。这两种方法的使用要视情况而定。注意:unicode -> str 是编码过程(encode()); str -> unicode 是解码过程(decode())。示例如下:
# --coding:utf-8-- #import requestsresponse = requests.get("https://baidu.com/")print response.urlprint type(response.content)with open("c:\\users\\administrator\\desktop\\content.html", "w") as f: f.write(response.content) print "content保存成功"print type(response.text)with open("c:\\users\\administrator\\desktop\\text.html", "w") as f: # 返回url的编码方式 print response.encoding f.write(response.text.encode("iso-8859-1")) print "text保存成功"
2. 发送get请求,直接调用“resquests.get" 就可以了。response的一些属性:response.text; response.content; response.url; response.encoding; response.status_code
# --coding:utf-8-- #import requestsparams = { "wd": "中国"}headers = { "user-agent": "mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.62 safari/537.36"}response = requests.get("https://baidu.com/s", params=params, headers=headers)print response.urlwith open("c:\\users\\administrator\\desktop\\get.html", "w") as f: f.write(response.content) print "保存成功"
3. 发送post请求:传入data信息。注意get请求传入的是params信息。示例如下:
# --coding:utf-8-- #import requestsdata = { "first": "true", "pn": "1", "wd": "python"}headers = { "referer": "https://www.lagou.com/jobs/list_python?labelwords=&fromsearch=true&suginput=", "user-agent": "mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.62 safari/537.36"}response = requests.post("https://www.lagou.com/jobs/positionajax.json?needaddtionalresult=false", data=data, headers=headers)print response.encodingprint type(response.content)with open("c:\\users\\administrator\\desktop\\post.html", "w") as f: f.write(response.content) print "保存成功"
4. 使用代理。在get方法中增加proxy参数即可。示例代码如下:
# --coding:utf-8-- #import requestsproxy = { "http": "124.42.7.103"}response = requests.get("http://httpbin.org/ip", proxies=proxy)print response.content
5. requests处理cookies信息。使用requests.session()方法即可。示例代码如下:
# --coding:utf-8-- #import requestsurl = "http://www.renren.com/plogin.do"# url = "http://www.renren.com/syshome.do"data = {"email": "账号", "password": "密码"}headers = { "user-agent": "mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.62 safari/537.36"}session = requests.session()session.post(url, data=data, headers=headers)response = session.get("http://www.renren.com/543484094/profile")with open("c:\\users\\administrator\\desktop\\liwei.html", "w") as fp: fp.write(response.content) print "保存成功"
6. 处理不信任的ssl证书。与上面的代码相比,多了一个verify=false参数,为了处理ssl证书不受信用的问题。
示例代码如下:
response = session.get("http://www.renren.com/543484094/profile", verify=false)
以上就是关于requests库的基本使用。
本文讲解了requests库的基本使用 ,更多相关内容请关注。
相关推荐:
前端调用微信支付接口
jquery对象与dom对象
jquery插件开发标准写法
以上就是requests库的基本使用的详细内容。
其它类似信息

推荐信息