一,安装

  pip install requests

二,基本用法

1.简单示例

import requestsres = 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 reheaders = {"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。

转载于:https://www.cnblogs.com/zivli/p/10919592.html

爬虫—使用Requests相关推荐

  1. 爬虫之requests模块发送post请求

    爬虫之requests模块发送post请求 思考:哪些地方我们会用到POST请求? 登录注册( 在web工程师看来POST 比 GET 更安全,url地址中不会暴露用户的账号密码等信息) 需要传输大文 ...

  2. 爬虫之requests模块超时参数timeout的使用

    爬虫之requests模块超时参数timeout的使用 在平时网上冲浪的过程中,我们经常会遇到网络波动,这个时候,一个请求等了很久可能任然没有结果. 在爬虫中,一个请求很久没有结果,就会让整个项目的效 ...

  3. 爬虫之requests模块cookieJar对象转换为cookies字典的方法

    爬虫之requests模块cookieJar对象转换为cookies字典的方法 使用requests获取的resposne对象,具有cookies属性.该属性值是一个cookieJar类型,包含了对方 ...

  4. 爬虫之requests模块中cookies参数的使用

    爬虫之requests模块中cookies参数的使用 上一篇文章在headers参数中携带cookie,也可以使用专门的cookies参数 cookies参数的形式:字典 cookies = {&qu ...

  5. 爬虫之requests模块在headers参数中携带cookie发送请求

    爬虫之requests模块在headers参数中携带cookie发送请求 网站经常利用请求头中的Cookie字段来做用户访问状态的保持,那么我们可以在headers参数中添加Cookie,模拟普通用户 ...

  6. 爬虫之requests模块发送带参数的请求

    爬虫之requests模块发送带参数的请求 我们在使用百度搜索的时候经常发现url地址中会有一个 ?,那么该问号后边的就是请求参数,又叫做查询字符串 1.1 在url携带参数 直接对含有参数的url发 ...

  7. 爬虫之requests模块发送带header的请求

    爬虫之requests模块发送带header的请求 我们先写一个获取百度首页的代码 import requestsurl = 'https://www.baidu.com'response = req ...

  8. 爬虫之requests模块介绍

    爬虫之requests模块介绍 requests文档http://docs.python-requests.org/zh_CN/latest/index.html      [文档中包括的快速上手要精 ...

  9. python requests_Python爬虫之requests模块

    # requests模块 知识点: 掌握 headers参数的使用 掌握 发送带参数的请求 掌握 headers中携带cookie 掌握 cookies参数的使用 掌握 cookieJar的转换方法 ...

  10. python构造响应头_Python爬虫库requests获取响应内容、响应状态码、响应头

    首先在程序中引入Requests模块 import requests 一.获取不同类型的响应内容 在发送请求后,服务器会返回一个响应内容,而且requests通常会自动解码响应内容 1.文本响应内容 ...

最新文章

  1. 这个Spring循环依赖的坑,90%以上的人都不知道
  2. [USACO16JAN]Angry Cows S[二分+贪心]
  3. 智能音箱 之 麦克风参数介绍
  4. Spring&Quartz集成自定义注释
  5. java 虚类private 继承_Java经典面试36题和答案
  6. Ubuntu: 创建PlayOnLinux快捷键 Create PlayOnLinux Application Desktop
  7. spirng整合rmi
  8. mac终端编写c语言,【新手提问】有知道用mac终端编c语言的网络编程的人吗?
  9. nyoj35 表达式求值
  10. centos用ifconfig不显示ip地址的解决方法
  11. 我需要一个足够大的桌子
  12. go项目实战 <微信公众号后台开发>(一、获取token)
  13. python工资高还是java-python工资高还是java?python和java薪资对比
  14. 开放的在线客服系统Live Zilla
  15. 40款非常漂亮的免费下载 HTML5 CSS3 网站模板欣赏
  16. [UE4]打包运行时提示Plugin ‘‘ failed to load because module ‘‘ could not be found.缺少插件解决方法
  17. 计算机考研所用教材,计算机考研经验及所用教材
  18. 戴尔服务器安装系统出现蓝屏重启,服务器安装系统蓝屏原因_dell服务器安装系统设计.docx...
  19. Fortran语言的入门与心得
  20. Maven setting配置文件

热门文章

  1. mysql+基本代码_PHP+MySQL扎实基本功十句话_php
  2. myeclipse 编写html,myeclipse怎么写html
  3. 555定时器回差电压计算公式_555定时器及其应用
  4. php和全栈,php与h5全栈工程师是什么意思
  5. Java jni 底层_JAVA语言语言调用底层语言的技术JNI解析
  6. 小学计算机打字比赛教案,小学信息技术二年级教案
  7. c语言课程设计六角填数,关于蓝桥杯C语言B组的六角型答案问题
  8. python json操作_Python读取JSON数据操作实例解析
  9. camerax_Android CameraX概述
  10. jdbc连接池工作原理_JDBC连接实际上如何工作?