爬虫—使用Requests

一,安装

  pip install requests

二,基本用法

1.简单示例

import requests

res = requests.get('https://www.baidu.com')
print(type(res))
print(res.status_code)
print(res.text)
print(type(res.text))
print(res.cookies)

运行结果:

<class 'requests.models.Response'>
200
<!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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://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>

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

  通过运行结果可发现,它返回的类型是requests.models.Response,响应体字符串类型是str,Cookie的类型是RequestsCookieJar。

2.GET请求

  这里使用httpbin测试接口进行测试,httpbin这个网站能测试 HTTP 请求和响应的各种信息,比如 cookie、ip、headers 和登录验证等,且支持 GET、POST 等多种方法,对 web 开发和测试很有帮助。它由 Python + Flask 编写,是一个开源项目(官方网站:http://httpbin.org/开源地址:https://github.com/Runscope/httpbin)。  

# GET请求
res = requests.get('https://httpbin.org/get')
print(res.text)

运行结果:

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "183.129.61.183, 183.129.61.183", 
  "url": "https://httpbin.org/get"
}

  可以发现,我们成功的发起了GET请求,返回的结果中包含请求头,URL,IP等信息。

♦传递参数

  对于GET请求,如何添加参数呢?比如name是rain,age是22。是不是需要写成:

  res = requests.get('https://httpbin.org/get?name=rain&age=22')

  其实这样也可以,但是这种数据信息一般使用字典来存储。

# 带参数
data = {
    'name': 'rain',
    'age': 22
}
res = requests.get('https://httpbin.org/get',params=data)
print(res.text)

  运行结果:

{
  "args": {
    "age": "22", 
    "name": "rain"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "183.129.61.183, 183.129.61.183", 
  "url": "https://httpbin.org/get?name=rain&age=22"
}

  可以看到,请求的连接被自动构造成了:https://httpbin.org/get?name=rain&age=22。

  需要注意的是网页返回的类型实际上是str类型,但其格式为JSON字符串,想要解析结果,获得一个字典类型的话,可以直接调用json()方法:

# 转成字典
print(type(res.json()))

结果:
<class 'dict'>

  如果返回的类型不是JSON类型,此时调用json()方法,就会抛出json.decoder.JSONDecoderError异常。

♦抓取网页

  如果请求普通的网页,就能获得相应的内容。下面以“知乎“的”发现“页面为例:

# 抓取网页,发现—知乎
import requests
import re

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
}
res = requests.get('https://www.zhihu.com/explore', headers=headers)
parse = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S)
text = re.findall(parse,res.text)
print(text)

  这里我们加入了,headers信息,也就是user-agent字段信息,也就是浏览器标识。如果不加上这个,就会被禁止抓取。之后使用正则表达式匹配出a节点里面的问题内容。结果如下:

['\n现在的复古8-bit风格游戏和当时真正的8-bit游戏有哪些差别?\n', '\n如何评价罗云熙在《白发》中饰演的容齐?\n', '\n为什么要把敦煌莫高窟建在西北地区?\n', '\n猫的哪些行为会让你觉得猫是爱你的?\n', '\n老人总是通过骗孩子的方式让孩子服从自己的命令,这种情况怎么办?\n', '\n如何看待faker在直播中说白银怎么喜欢闪现放D?\n', '\n有哪些女演员在影视剧中的扮相让你惊艳?\n', '\nPowerPoint 到底有多厉害?\n', '\n如何评价华晨宇?\n', '\n毛细现象水液面是不是球面的一部分?\n']
♦抓取二进制数据

  浏览网页时,我们经常看到页面中会有图片,音频,视频等文件。这些文件本质上由二进制码组成的,使用了特定的保存格式和对应的解析方式,我们才得以看到这些形形色色的多媒体。想要抓取他们,就需要拿到其二进制码。

  以GitHub站点的图标为例:

# 抓取二进制文件
res = requests.get('https://github.com/favicon.ico')
print(res.text)
print(res.content)

  这里抓取的是站点图标,就是浏览器每一个标签上显示的小图标,如下图:

                                   

  这里打印了text和content,结果如下:

                                                                        +++G��������G+++                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
b'\x00\x00\x01\x00\x02\x00\x10\x10\x00\x00\x01\x00 \x00(\x05\x00\x00&\x00\x00\x00  \x00\x00\x01\x00 \x00(\x14\x00\x00N\x05\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00 

  可以看到前者出现了乱码,后者开头带上了一个b,说明是bytes类型。由于是二进制数据,所有text打印时转化成str类型,图片直接转化为字符串,自然就会出现乱码。接下来,我们将图片保存下来:

res = requests.get('https://github.com/favicon.ico')
with open('favicon.ico','wb') as f:
    f.write(res.content)

  使用open()方法以二进制写的形式打开文件,向文件里写入二进制数据。之后我们打开刚才写入的文件:

                           

  这里可以看到,成功的获取到了网页上面的图标信息,同样的音频和视频也可以使用这种方法来获取。

 

 3.POST请求

  使用requests发送POST请求也同样简单:

# POST请求
data = {
    'name':'rain',
    'age':'22'
}
res = requests.post('https://httpbin.org/post',data=data)
print(res.text)

  运行结果:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "age": "22", 
    "name": "rain"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "16", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "183.129.61.183, 183.129.61.183", 
  "url": "https://httpbin.org/post"
}

  可以看到,我们成功的获取了返回结果,其中form里面的数据就是提交的数据,也证明了POST请求成功。

4.响应信息

  发送请求成功后,得到的自然是相应。上面的例子中,我们使用text和content获取了响应的内容。此外还有很多方法可以用来获取响应的其他信息:

# 获取响应信息
res = requests.get('http://www.baidu.com')
print(type(res.status_code), res.status_code)   # 响应状态码
print(type(res.headers), res.headers)           # 响应头信息
print(type(res.cookies), res.cookies)           # Cookies信息
print(type(res.url), res.url)                   # 请求url
print(type(res.history), res.history)           # 请求历史信息

  运行结果:

<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Fri, 24 May 2019 10:02:25 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:37 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
<class 'str'> http://www.baidu.com/
<class 'list'> []

  其中响应状态码经常用来判断请求是否成功,而requests还提供了一个内置的状态码查询对象requests.codes:

# requests内置状态码查询
res = requests.get('http://www.baidu.com')
exit() if not res.status_code == requests.codes.ok else print("Request Successful!")

  运行结果:

Request Successful!

  这里通过响应信息中的请求成功状态码与requests内置请求成功状态码进行比较来判断请求是否成功。其中requests.codes.ok的值为200。

posted @ 2019-05-24 18:12  ZivLi  阅读(1054)  评论(0编辑  收藏  举报