小白学爬虫——Requests.get
r=requests.get(url)
通过该方法构造一个向服务器请求资源的Request对象(requests库内部生成的)。
返回的内容保存在变量r中,r是一个返回服务器所有资源的Response对象
requests.get函数完整的使用方法:
requests.get(url,params=None,kwargs)
url:拟获取页面的url链接
params:url中的额外参数,包括字典或字节流格式,可选
**kwargs:12个控制访问的参数,可选
其中Request对象和Response对象都是重点,而Response对象更是重中之重,其包含了爬虫返回的内容。下面我们来看一下Response对象的属性。
Response对象的属性
属性 | 说明 |
---|---|
r.status_code | HTTP请求的返回状态,200表示连接成功,404或其他表示失败 |
r.text | HTTP响应内容的字符串形式,即url对应的页面内容 |
r.encoding | 从HTTP header 中猜测的响应内容编码方式 |
r.apparent_encoding | 从内容中分析出的响应内容编码方式 (备选编码方式) |
r.content | HTTP响应内容的二进制形式 |
使用get方法获取网页资源时的流程:
用r.status_code来检查返回的Response对象的状态
返回200——使用其他属性来解析返回的内容
返回404或其他——说明url的访问因某种原因而异常
下面我们来实践一波
>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200
>>> 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=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç\x99¾åº¦ä¸\x80ä¸\x8bï¼\x8cä½\xa0å°±ç\x9f¥é\x81
\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div
class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg>
<img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129>
</div> <form id=form name=f action=//www.baidu.com/s class=fm> <input
type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8>
<input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1>
<input type=hidden name=rsv_idx value=1> <input type=hidden name=tn
value