【02】Python爬虫:Requests的基本用法

转载自公众号:pythongeek

虽然Python有内置的urllib库,可以实现网络的请求,但是我并不推荐。因为urllib在很多时候使用起来不方便,比如加一个代理,处理Cookie时API都很繁琐,再比如发送一个POST请求也很麻烦。

而Requests就相当于urllib的升级版本,简化了urllib的使用方法。有了Requests,我们可以用几句代码实现代理的设置,Cookie的设置,非常方便。下面我就给大家整理了Requests库的使用方法和细节。详细可以参考Requests官方文档。

什么是Requests?

Requests是Python语言编写,基于urllib3,采用Apache2 Licensed开源协议的HTTP库。

它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。是Python实现的简单易用的HTTP库。

安装也很简单:pip install requests

Requests的语法操作

1. 实例引入

import requests

response = requests.get('http://www.baidu.com/')
print(response.status_code)
print(type(response.text))
print(response.text)    # HTML网页源码
print(response.cookies)

运行结果:

200
<class 'str'>
<!DOCTYPE html>
<!--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>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</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=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§é¢</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç»å½</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">ç»å½</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ´å¤äº§å</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å³äºç¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使ç¨ç¾åº¦åå¿è¯»</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æè§åé¦</a>&nbsp;京ICPè¯030173å·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>

2. 各种请求方式

import requests

requests.get('http://httpbin.org/get')     # 发送get请求
requests.post('http://httpbin.org/post')    # 发送post请求,只要调用一个post方法,传入一个url参数
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')

官方文档里提供的这个网址足够我们测试这些请求方式了。

请求

1. 基本GET请求

import requests

resp = requests.get('http://httpbin.org/get')
print(resp.text)

这个我们前面有使用过,也是最常用的方法。运行成功就可以看到网页的源码了。

2. 带参数的的GET请求

import requests

data = {
    'name' : 'Jack',
    'age' : 20
}
resp = requests.get('http://httpbin.org/get',params = data)
print(resp.text)

传入参数只需要我们把数据生成一个字典,然后调用params参数,赋值给他就可以,是不是很方便。

3. 解析json

import requests
import json

resp = requests.get('http://httpbin.org/get')
print(resp.text)
print(resp.json())
print(json.load(resp.text))
print(type(resp.json()))

运行结果:

{
Traceback (most recent call last):
  "args": {}, 
  "headers": {
  File "C:/Users/CALL_ME_K/PycharmProjects/Python_FullStack/day12/day12_s1.py", line 7, in <module>
    "Accept": "*/*", 
    print(json.load(resp.text))
    "Accept-Encoding": "gzip, deflate", 
  File "D:\Python\Python36\lib\json\__init__.py", line 296, in load
    "Connection": "close", 
    return loads(fp.read(),
    "Host": "httpbin.org", 
AttributeError: 'str' object has no attribute 'read'
    "User-Agent": "python-requests/2.19.1"
  }, 
  "origin": "211.97.3.137", 
  "url": "http://httpbin.org/get"
}

{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.19.1'}, 'origin': '211.97.3.137', 'url': 'http://httpbin.org/get'}

可以看出Requests的jaon解析和json的loads方法解析出来的结果是完全一样的。所以Requests可以很方便的解析json数据。

4. 获取二进制数据

import requests

resp = requests.get('http://www.baidu.com/img/baidu_jgylogo3.gif')
print(resp.content)
print(resp.text)

运行成功我们可以看到content方法获取的图片页面源码是二进制数据,而text获取的则是字符串代码。显然获取图片这种二进制数据需要使用content方法。

with open('logo.gif','wb') as f:
    f.write(resp.content)

这样我们就保存了图片,我们可以在文件夹下看到这张图片。

5. 添加headers

import requests

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360EE'}
resp = requests.get('http://www.baidu.com', headers=headers)
print(resp.text)

有些网页如果我们直接去请求的话,他会查看请求的对象是不是浏览器,如果没有浏览器信息就会禁止我们爬虫的访问,这个时候我们就要给爬虫加一个headers,加一个浏览器的user-agent信息。这样我们就可以正常访问了。如果有的伙伴不知道怎么得到User-Agent,可以打开浏览器的审查元素,找到network,随便点击一个链接就可以看到User-Agent的信息了。

6. 基本POST请求

import requests

data = {
    'name' : 'jack',
    'age' : 20
}
resp = requests.post('http://httpbin.org/post', data=data)
print(resp.text)

一个POST必然是要有一个Form Data的表单提交的,我们只要把信息传给data参数就可以了。一个POST请求只需要调用post方法,是不是特别方便呢。如果不觉得方便的话,可以去参考urllib的使用方法。

响应

1. response属性

import requests

response = requests.get('http://www.baidu.com/')
print(type(response.status_code))   # 状态码
print(type(response.text))  # 网页源码
print(type(response.headers))   # 头部信息
print(type(response.cookies))   # cookies
print(type(response.url))   # 请求的url
print(type(response.history))   # 访问的历史纪录

获取这些信息只需要简单的调用就可以实现了。

2. 状态码判断

import requests

response = requests.get('http://www.baidu.com/')
exit() if not response.status_code == 200 else print('Successful')

如果发送了一个错误请求(一个4XX客户端错误,或者5XX服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:

bad_r = requests.get('http://httpbin.org/status/404')
print(bad_r.status_code)
bad_r.raise_for_status()

得到输出结果:

404
Traceback (most recent call last):
  File "C:/Users/CALL_ME_K/PycharmProjects/Python_FullStack/day12/day12_s1.py", line 8, in <module>
    bad_r.raise_for_status()
  File "D:\Python\Python36\lib\site-packages\requests-2.19.1-py3.6.egg\requests\models.py", line 943, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND for url: http://httpbin.org/status/404

好了,这篇文章我们了解了Requests库的基本语法操作,相信大家对Requests库的请求和响应已经很清楚了,大家完全可以抓取一些网页了。

猜你喜欢

转载自blog.csdn.net/CALL_ME_K/article/details/81282402