crawler-02 requests库入门

crawler-02 requests库入门

  requests库是python的第三方库,是目前公认的爬去网页最好的第三方库,简单简洁。

一、requests库安装使用

1、requests库安装

1
pip install requests

1Ea15d.png

2、IDLE测试requests库

1
2
3
4
5
6
>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200
>>> r.encoding='utf-8'
>>> r.text

1Ea8PA.png

1EaJ2t.png

  可以看到百度首页的内容已被成功抓取。

3、爬取网页的通用代码框架

  网页连接有风险,异常处理很重要,常见异常如下:

1EaB5j.png

1
2
3
#异常处理方法
#能够判断返回状态码是否200
r.raise_for_status #如果不是200,产生异常requests.HTTPError

通用代码框架

1
2
3
4
5
6
7
8
9
10
#爬取网页通用代码框架

def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status() #如果返回状态不是200,产生异常requests.HTTPError
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"

应用举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status() #如果返回状态不是200,产生异常requests.HTTPError
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"

def main():
url="http://www.baidu.com"
url1 = "www.baidu.com"
print(getHTMLText(url1)) #产生异常
print("==============================")
print(getHTMLText(url)) #正常返回结果

if __name__ == '__main__':
main()

二、requests库的7个主要方法

方法说明

1EarPs.png

http协议对对资源的操作

1EasGn.png

1、get() 方法

1
2
3
4
5
6
7
8
9
10
#简单使用
r = requests.get(url)

#完整参数
requests.get(url,params=None,**kwargs)

#参数解析
url:目标页面链接
params:额外参数,字典或者字节流格式,可选
**kwargs:12和控制访问的参数,可选

1)Request:构造一个向服务器请求资源的Request对象;

2)Response:返回一个包含服务器资源的Response对象,包含了爬虫返回的内容;

3)Response对象:

1
2
3
4
5
6
7
8
9
>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200 #状态码
>>> type(r)
<class 'requests.models.Response'> #返回类型是一个类,类名Response
>>> r.headers #Response返回的头部信息
{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 09 Dec 2019 02:43:53 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:12 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
>>>

1Ea6x0.png

4)解码

 r.encoding:其编码方式是从http header中的charset字段获取的。如果header中存在charset字段,那么说明我们访问的服务器对编码方式有要求,该编码被获取回来保存在r.encoding中;如果header中不存在charset字段,则默认编码为’ISO-8859-1’,但是该编码不能解析中文。

 r.apparent_encoding:不是从http header获取编码了,而是从网页内容上分析可能出现的文本编码形式,因此这种编码比r.encoding更加准确一些。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200 #状态码
>>> r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'
>>> r.text
#此时得到的全是英文

>>> r.encoding=r.apparent_encoding
>>> r.text
#此时得到的包含了中文

如下图:

1EaRqU.png

2、patch和put的区别

1EafZF.png

3、head() 方法

  用少量网络流量获取网络资源的概要信息

1
2
3
4
5
6
7
>>> import requests
>>> r=requests.head('http://httpbin.org/get')
>>> r.headers
{'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', 'Content-Encoding': 'gzip', 'Content-Type': 'application/json', 'Date': 'Mon, 09 Dec 2019 03:37:52 GMT', 'Referrer-Policy': 'no-referrer-when-downgrade', 'Server': 'nginx', 'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'DENY', 'X-XSS-Protection': '1; mode=block', 'Connection': 'keep-alive'}
>>> r.text
''
>>>

4、post() 方法

  向服务器提交新增数据,如下,字典payload保存键值对,post() 方法提交该字典。当我们向url去post一个字典或者键值对的时候,该键值对默认是保存在form表单等字段下的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> import requests
>>> payload = {'key1': 'value1','key2': 'value2'}
>>> r=requests.post('http://httpbin.org/post',data=payload)
>>> print(r.text)
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1", #键值对保存到了表单里
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.21.0"
},
"json": null,
"origin": "112.24.5.77, 112.24.5.77",
"url": "https://httpbin.org/post"
}

>>>

假如提交的不是键值对,例如下面,提交的就是普通字符串,保存到了data字段下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> r=requests.post('http://httpbin.org/post',data='ABC')
>>> print(r.text)
{
"args": {},
"data": "ABC", #字符串保存到了data字段下
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "3",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.21.0"
},
"json": null,
"origin": "112.24.5.77, 112.24.5.77",
"url": "https://httpbin.org/post"
}

>>>
欢迎打赏,谢谢
------ 本文结束------
0%