Python爬虫库requests获取响应内容、响应状态码、响应头
(编辑:jimmy 日期: 2024/11/19 浏览:3 次 )
首先在程序中引入Requests模块
import requests
一、获取不同类型的响应内容
在发送请求后,服务器会返回一个响应内容,而且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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>"bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>"http://www.baidu.com/bdorz/login.gif" rel="external nofollow" " "" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">"display: block;">"htmlcode">r.encoding'ISO-8859-1'2.二进制响应内容
r.content # 通过content获取的内容便是二进制类型的3.JSON响应内容
r.json()4.原始响应内容
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_code200判断响应状态码
r.status_code == requests.codes.okTrue当发送一个错误请求时,抛出异常
bad_r = requests.get('http://httpbin.org/status/404') print(bad_r.status_code) bad_r.raise_for_status()404 --------------------------------------------------------------------------- HTTPError Traceback (most recent call last) <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() D:\Anaconda3\lib\site-packages\requests\models.py in raise_for_status(self) 926 927 if http_error_msg: --> 928 raise HTTPError(http_error_msg, response=self) 929 930 def close(self): HTTPError: 404 Client Error: NOT FOUND for url: http://httpbin.org/status/404三、响应头
获取响应头
r = requests.get('https://www.baidu.com') r.headers{'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'))bfe/1.0.8.18 bfe/1.0.8.18更多关于Python爬虫库requestsr的使用方法请查看下面的相关链接
下一篇:python add_argument()用法解析