一、获取不同类型的响应内容
在发送请求后,服务器会返回一个响应内容,而且requests通常会自动解码响应内容
1.文本响应内容
获取文本类型的响应内容
r = requests.get('https://www.baidu.com')
r.text # 通过文本的形式获取响应内容
' !DOCTYPE html \r\n !--STATUS OK-- html head meta http-equiv=content-type content=text/html;charset=utf-8 meta http-equiv=X-UA-Compatible content=IE=Edge meta content=always name=referrer link rel=stylesheet type=text/css href=/uploads/cj/202001/error.html width=270 height=129 /div form id=form name=f action=//www.baidu.com/s "bg s_ipt_wr" input id=kw name=wd "bg s_btn_wr" input type=submit id=su value= \x99 o| \x80 \x8b autofocus /span /form /div /div div id=u1 a href=http://news.baidu.com name=tj_trnews ' a href="/uploads/cj/202001/error.html encodeURIComponent(window.location.href+ (window.location.search === " rel="external nofollow" " " " : "&")+ "bdorz_come=1")+ \'" name="tj_login" \x99 \x95 /a \r\n /script a href=//www.baidu.com/more/ name=tj_briicon '[!--empirenews.page--]r = requests.get('https://www.baidu.com',stream=True)
print(r.raw) # 就是urllib中的HTTPResponse对象
print(r.raw.read(10))
requests.packages.urllib3.response.HTTPResponse object at 0x00000077940AEEF0
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
二、响应状态码
获取响应状态码
r = requests.get('https://www.baidu.com')
r.status_code
ipython-input-15-9b812f4c5860 in module ()
1 bad_r = requests.get('http://httpbin.org/status/404')
2 print(bad_r.status_code)
---- 3 bad_r.raise_for_status()
{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 23 Jul 2018 09:04:12 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:51 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
获取响应头的具体字段
print(r.headers['Server'])
print(r.headers.get('Server'))
转载:非常欢迎各位朋友分享到个人站长或者朋友圈,但转载请说明文章出处“黎青松SEO博客”。