小白学爬虫——Requests.get()

这篇博客是小白学爬虫系列的一部分,重点介绍了`requests.get()`函数的使用。文章详细阐述了如何通过`requests.get(url)`发送HTTP请求,并获取Response对象。Response对象包含服务器返回的所有资源,其关键属性如`status_code`用于检查请求状态,`encoding`和`apparent_encoding`用于确定正确的文本编码。当遇到乱码问题时,`apparent_encoding`通常能提供更准确的编码解决方案。
摘要由CSDN通过智能技术生成

小白学爬虫——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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值