当前位置: 首页 > 工具软件 > Requests > 使用案例 >

Python爬虫之Requests功能分解

苗信鸥
2023-12-01

作者简介:大家好,我是车神哥,府学路18号的车神磊
⚡About—>车神:从寝室实验室快3分钟,最慢3分半(那半分钟其实是等绿
个人主页:车手只需要车和手,压力来自论文_府学路18号车神_CSDN博客
磊 官方认证:人工智能领域优质创作者
点赞评论收藏 == 养成习惯一键三连)

⚡希望大家多多支持珞~一起加油 


前言

Requests的主要功能及用途是用作发送网络请求,根据对方服务器的要求不同,可使用GETPOSTPUT等方式进行请求。并且可以对请求头进行伪装使用代理访问等。安装完成后,先从一些简单的例子开始了解Requests的使用方法。

使用GET和POST请求

在HTTP中常见发生网络请求的方式有两种,GET和POST。GET是从指定的资源请求数据,POST是向指定的资源提交要被处理的数据。

GET请求

  • 使用Requests发送GET请求将百度搜索的页面源数据爬取出来。(下面尝试一下)
>>> import requests			# 引入库
>>> r = requests.get('https://www.baidu.com')		# 向百度网页发送请求并返回一个对象
>>> r						# 输出
<Response [200]>

从上可知获得了一个名为rresponse对象。访问成功后,所以的网页信息都会储存在这个r中。如果看不见这个对象,那么需要把这个对象提出来以字符串的格式进行显示。

>>> 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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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=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=ç\x99¾åº¦ä¸\x80ä¸\x8b class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ\x96°é\x97»</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>å\x9c°å\x9b¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§\x86é¢\x91</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å\x90§</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>ç\x99»å½\x95</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">ç\x99»å½\x95</a>\');\r\n                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å\x85³äº\x8eç\x99¾åº¦</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/>使ç\x94¨ç\x99¾åº¦å\x89\x8då¿\x85读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

以上打印的内容即为HTML源码,因为百度搜索的页面元素不多,所以较短。

POST请求

  • 利用post的方法向httpbin.org网站发送一个请求,并且拉取返回数据。

>>> import requests
>>> r = requests.post('http://httpbin.org/post', data={'key':'value'})
>>> r = r.text
>>> r 
'{\n  "args": {}, \n  "data": "", \n  "files": {}, \n  "form": {\n    "key": "value"\n  }, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Content-Length": "9", \n    "Content-Type": "application/x-www-form-urlencoded", \n    "Host": "httpbin.org", \n    "User-Agent": "python-requests/2.27.1", \n    "X-Amzn-Trace-Id": "Root=1-62559e95-0787c2835350a9d4752336b5"\n  }, \n  "json": null, \n  "origin": "125.33.161.73", \n  "url": "http://httpbin.org/post"\n}\n'

从上面返回的数据来看,是一大堆json数据。

由于常用的也就是这里介绍Get和POST这两种请求方式,当然还有其他的,如PUT DELECT,还有OPTIONS。

通过URL来传递参数

需要知道的是URL不仅是一个网址,平时在访问网站的时候,会经常后面带很长一串的字符串,这些个字符串就是所谓的请求参数。

如果分析URL的话,我们可以发现这里面会有很多类似key/value的键和值。Requests允许通过字典或者字符串来传参。

例如:

>>> payload = {"key1":"value1", "key2":"value2", "key3":"value3"}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> r
<Response [200]>
>>> r.url
'http://httpbin.org/get?key1=value1&key2=value2&key3=value3'

这样就把参数传入来URL中。

当然,在面对较多的参数,比如有列表,同样也可以传入到其中。

>>> payload = {"key1":"value1", "key2":"value2", "key3":["value3","value4","value5"]}
>>> r = requests.get('http://httpbin.org/get', params=payload)
>>> r.url
'http://httpbin.org/get?key1=value1&key2=value2&key3=value3&key3=value4&key3=value5'

设置超时

在请求的时候设置超时等待时间,可避免等待太久。

在请求的时候给参数timeout附上一个数字,单位为秒。

如果请求超过此时,则会断开报错。

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "/Users/yurbro./Desktop/pythonVirtualenv/venv/lib/python3.7/site-packages/urllib3/connection.py", line 175, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw
  File "/Users/yurbro./Desktop/pythonVirtualenv/venv/lib/python3.7/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/Users/yurbro./Desktop/pythonVirtualenv/venv/lib/python3.7/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
socket.timeout: timed out

查看返回内容

将返回的reponse对象打印出来,在查看其中的内容。

>>> import requests
>>> r = requests.get('http://api.github.com/events')
r>>> r.text
'[{"id":"21272029711","type":"PullRequestEvent","actor":{"id":49699333,"login":"dependabot[bot]","display_login":"dependabot","gravatar_id":"","url":"https://api.github.com/users/dependabot[bot]","avatar_url":"https://avatars.githubusercontent.com/u/49699333?"},"repo":{"id":205361298,"name":"evemonk/evemonk-sidekiq","url":"https://api.github.com/repos/evemonk/evemonk-sidekiq"},"payload":{"action":"opened","number":560,"pull_request":{"url":"https://api.github.com/repos/evemonk/evemonk-sidekiq/pulls/560","id":909043666,"node_id":"PR_kwDODD2Qks42LufS",

返回的内容很大一串,就不附上了。

当我们发起一个请求的时候,Requests会根据HTTPheaders进行编码。

>>> r.encoding
'utf-8'

当然,如果不满意源编码方式的话,可以自己修改哦~不过不太推荐

>>> r.encoding = 'ISO-8859-1'
>>> r.encoding
'ISO-8859-1'

从上面返回的值可以看出,已经修改好了编码方式。

设置请求头

HTTP消息头,以明文的字符串格式传送,是以冒号分隔的键/值对。如:Accept-Charset:utf-8.

HTTP消息头——指的是客户端或服务器响应的时候传递的头部信息,内容包含了浏览器信息、请求数据类型等。发送请求的时候消息头称为请求头,服务器返回内容时的消息头称为响应头。

若发现请求不到数据,而又没加请求头,在确认请求正确之前,多半是爬虫的身份被发现了。

由此,作为一个爬虫,必须让自己看起来不像是爬虫(需要伪装)。设置请求头,可以让爬虫的爬取过程看起来是一个用户在使用浏览器浏览网页一样。

>>> url = 'https://www.example.com'
>>> header = {'user-agent':'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; Fr) Presto/2.9.168 Version/11.52'}
>>> r = requests.get(url, header)
>>> r
<Response [200]>
>>> r.text
'<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset="utf-8" />\n    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />\n    <meta name="viewport" content="width=device-width, initial-scale=1" />\n    <style type="text/css">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 2em;\n        background-color: #fdfdff;\n        border-radius: 0.5em;\n        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        div {\n            margin: 0 auto;\n            width: auto;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is for use in illustrative examples in documents. You may use this\n    domain in literature without prior coordination or asking for permission.</p>\n    <p><a href="https://www.iana.org/domains/example">More information...</a></p>\n</div>\n</body>\n</html>\n'

复杂的Post请求

今天先学到这,乏了。还有项目、课题、零碎片化的时间学习新知识,哎~每天无情被卷(2022.4.17 23:13)


❤坚持读Paper,坚持做笔记,坚持学习,坚持刷力扣LeetCode❤!!!
坚持刷题!!!
To Be No.1

⚡⚡


创作不易⚡,过路能❤关注收藏点个赞三连就最好不过了

ღ( ´・ᴗ・` )

 类似资料: