R语言爬虫系列3|HTTP协议

浏览: 3715

image.png

要想使用R语言从网络抓取数据,我们就必须对R语言进行设置使得R具备与服务器及Web服务进行通信的能力。而互联网中进行网络通信的通用语言就是HTTP(HypterText Transfer Protocol),即所谓超文本传输协议。那这个超文本传输协议是个什么东西呢?

 

超文本协议是一种用于分布式、协作式和超媒体信息系统的应用层协议,是一个客户端终端(用户)和服务器终端(网站)请求和应答的标准(TCP),通过使用网页浏览器、网络爬虫或者其他工具,客户端发起一个HTTP请求到服务器上指定端口(默认端口为80)来获取网络资源的过程。说人话HTTP就是浏览器或者爬虫工具如何来接收网页HTML的方法。

 

实际生活中,当我们坐在电脑前,用浏览器访问淘宝进行购物,其间我们基本上不会与HTTP打交道。创建和发送HTTP请求以及处理服务器端返回的HTTP响应都是由浏览器一手搞定,试想一下如果大家每次用淘宝购物都需要手动构建类似“用HTTP协议把www.taobao.com网页下的某个商品链接传递给我”这样的请求,岂不是非常坑爹?虽然很坑爹,但我们现在需要用R语言来做一次,看看R在进行爬虫时如何来模拟浏览器和网络通信的任务。为了满足我们多样的爬虫需求,我们必须深入学习一下网络中文件传输协议并准确构建请求。

 

访问NBA中文网主页

image.png

louwill先给大家看一个在访问NBA中文网主页的时候浏览器是如何通过HTTP协议帮我们构建请求以及服务器是如何相应我们的请求的。在这个例子中,我们首先建立了到http://china.nba.com/的连接,并请求服务器发送index.html。HTTP客户端首先把主机翻译为一个IP地址并在缺省的HTTP端口(80端口)建立到服务器的连接。打个比方说,这个80端口就好比网络资源服务器所在的屋子的门,HTTP客户端就是通过敲正门来建立起连接的,相应的请求和响应过程总结如下:

客户端会话信息:

About to connect() to china.nba.com port 80 (#0)
  Trying 127.0.0.1:50049... connected
Connected to china.nba.com(127.0.0.1:50049) port 80 (#0)
Connected #0 to host china.nba.com left intact

建立连接之后,服务器会等待请求,浏览器会向服务器发送如下的HTTP请求:

GET /index.html  HTTP/1.1
Host: china.nba.com
Accept: text/html,application/xhtml+xml,application/xml;
q=0.9,image/webp,*/*;q=0.8
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 
(KHTML, like Gecko)Chrome/49.0.2623.221 Safari/537.36 SE 
2.X MetaSr 1.0

然后就是服务器该如何响应浏览器的请求了:

HTTP/1.1 200 OK
Date:Thu, 14 Sep 2017 06:34:35 GMT
Server:squid/3.5.20
Keep-Alive:timeout=38
Vary:Accept-Encoding
...



在接受了所有数据之后,连接会被浏览器再次关闭,一次访问就算结束了。

closing connection #0

URL语法

所谓URL,就是我们平常所说的网址,它的全称叫做统一资源定位符(Uniform Resource Locators),虽然URL不是HTTP的一部分,但通常我们能够通过URL直观地进行HTTP和其他协议的通信。总体的URL例子可以表示为:

scheme://hostname:port/path?querystring#fragment

对应到NBA中文网的实例为:

http://nbachina.qq.com/a/20170914/004815.htm

scheme表示URL的模式,它定义了浏览器和服务器之间通信所采用的协议,NBA主页的例子里采用的模式就是http。紧随其后的是主机名hostname和端口号port,主机名提供了存放我们感兴趣资源的服务器的名字,它是一个服务器的唯一识别符。端口号一般默认为80,主机名和端口号组合起来就等于说是告诉浏览器要去敲哪一扇门才能访问请求的资源。主机名和端口号之后的路径用来确定被请求的资源在服务器上的位置,跟文件系统类似,也是用/符号来分段的。

 

另外,在多数情形下,URL的路径里会提供很多补充信息,用来帮助服务器正确的处理一些复杂的请求,比如说通过类似name=value这样的查询字符串来获取更多的信息,或者用#符号来指向网页中特定的部分也是常见的补充方法。

 

最后需要说明的是,URL是通过ASCⅡ字符集来实现编码的,所有不在128个字符集里面的字符和特殊字符串都需要转义编码为标准的表示法,URL编码也被成为百分号编码,这是因为每个这样的编码都是以%开头的。在R语言中,我们可以通过基础函数URLencode()和URLdecode()函数来对字符串进行编码或者解码:

char <- "Golden states Worriors is the NBA Champion in 2017"
URLencode(char,reserve=TRUE)
[1] "Golden%20states%20Worriors%20is%20the%20NBA%20Champion%20in%202017"
URLdecode(char)
[1] "Golden states Worriors is the NBA Champion in 2017"

 

HTTP消息

HTTP消息无论是请求模式还是响应模式,都由起始行(start line)、标头(headers)(也叫消息报头)和正文(body)三部分组成。起始行是每个HTTP消息的第一行,它定义了请求使用的方法,以及所请求资源的路径和浏览器能够处理的HTTP最高版本。起始行之后的标头为浏览器和服务器提供了元信息,以“名字-取值”形式表示的一套标头字段。正文部分包含纯文本或者二进制数据,这由标头信息中的content-type声明决定。然后是MIME(多用途互联网邮件扩展)类型声明,这个声明的作用是告诉浏览器或服务器传输过来的是哪种类型的数据。起始行、标头和正文分开需要用到换行符(CRLF)。

 

在请求模式中,最常用的请求方法是GET和POST方法,在爬虫过程中至关重要。这两个方法都是从服务器请求一个资源,但是在正文的使用上有所不同,GET方法不会在请求的正文中发送任何内容,但POST会用正文来发送数据。

 

GET请求如下:

GET/form.html HTTP/1.1(CRLF)

在R中,RCurl包提供了一些高级函数来执行GET请求从Web服务器上获取某个资源,最常用的函数的getURL(),这个函数会自动确定主机、端口以及请求的资源。实际操作中,我们只需要把URL传给这个函数,也可以手动指定HTML表单参数:

library(RCurl)
getURL(http://nbachina.qq.com/a/20170914/004815.htm)
[1] "\ncharset=gb2312\" http-equiv=\"Content-Type\">\n
\n1tμ<c7><b6><d4>±è<bb>e<bc>yó<eb>2012à×<f6>a£o<b6><bc>·<c7><br style="margin: 0px; padding: 0px; max-width: 100%; word-wrap: break-word !important;"> ,... <truncated><br style="margin: 0px; padding: 0px; max-width: 100%; word-wrap: break-word !important;"></code></pre><p style="text-align: justify;">请求完后爬虫需求则依赖于后续的操作。</p><p style="text-align: justify;"> </p><p style="text-align: justify;">POST请求如下:</p><p style="text-align: justify;"></p><pre><code>POST/greetings.html HTTP/1.1</code></pre><p style="text-align: justify;">在R中执行POST请求,无需手动构建,而是可以使用postForm()函数:</p><p style="text-align: justify;"></p><pre><code>url<-“http://www.r-datacollection.com/materials/http/POSTexample.php”<br style="margin: 0px; padding: 0px; max-width: 100%; word-wrap: break-word !important;">cat(postForm(url,name=“Kobe”,age=39,style=“post”))<br style="margin: 0px; padding: 0px; max-width: 100%; word-wrap: break-word !important;">Hello Kobe!<br style="margin: 0px; padding: 0px; max-width: 100%; word-wrap: break-word !important;">You are 39 years old.<br style="margin: 0px; padding: 0px; max-width: 100%; word-wrap: break-word !important;"></code></pre><p style="text-align: justify;"></p><p style="text-align: justify;">在将预先声明的参数填充到表单中去的时候,需注意利用style参数预先显式声明一下其可接受的方式。常见的HTTP请求方法如下:</p><p>方法描述<br>GET从服务器检索资源<br>POST利用消息向服务器发送数据,然后从服务器检索资源<br>HEAD从服务器检索资源,但只响应起始行和标头<br>PUT将请求的正文保存在服务器上<br>DELETE从服务器删除一个资源<br>TRACE追踪消息到达服务器沿途的路径<br>OPTIONS返回支持的HTTP方法清单<br>CONNECT建立一个网络连接<br></p><p style="text-align: justify;"> </p><p style="text-align: justify;">浏览器发送请求后,服务器需要对其进行响应,会在响应的起始行发回一个状态码,可能大家会不太明白状态码是什么玩意儿,但louwill说一个404想必大家都知道了,404就是一个表示服务器无法找到资源的响应状态码。</p><p><img alt="image.png" src="https://cdn.hellobi.com/MzNV6gHesS.png" width="860" height="516"><br></p><p><span style="color: rgb(62, 62, 62);">而正常情形的响应状态码为200:</span><br></p><p><span style="color: rgb(62, 62, 62);"><img alt="image.png" src="https://cdn.hellobi.com/AH8GETSPF9.png" width="870" height="723"><br></span></p><p style="text-align: justify;">常见的HTTP状态码如下所示:</p><p style="text-align: justify;"><span style="color: rgb(0, 82, 255);">1xx:指示信息--表示请求已接收,继续处理</span></p><p style="text-align: justify;"><span style="color: rgb(0, 82, 255);">2xx:成功--表示请求已被成功接收、理解、接受</span></p><p style="text-align: justify;"><span style="color: rgb(0, 82, 255);">3xx:重定向--要完成请求必须进行更进一步的操作</span></p><p style="text-align: justify;"><span style="color: rgb(0, 82, 255);">4xx:客户端错误--请求有语法错误或请求无法实现</span></p><p style="text-align: justify;"><span style="color: rgb(0, 82, 255);">5xx:服务器端错误--服务器未能实现合法的请求</span></p><p style="text-align: justify;">常见的200表示成功找到资源,404表示未找到资源,500表示服务器内部错误,502表示错误网关等。</p><p style="text-align: justify;">有关爬虫基础部分的HTTP知识,louwill就给大家介绍到这里了,至于更深入的、更实际的一些情况,比如如何利用HTTP进行身份识别、认证和代理,libcurl库的详细介绍、RCurl的底层函数等其他内容将在R爬虫系列的后续内容中持续推出,也请各位期待~</p><p><span style="color: rgb(62, 62, 62);"><img alt="image.png" src="https://cdn.hellobi.com/IfXo3vAKTI.png" width="866" height="578"><br></span></p><p><strong>参考资料:</strong></p><p><span style="color: rgb(0, 122, 170);">Automated Data Collection with R</span></p><p><span style="color: rgb(2, 30, 170);"><br></span></p><p style="text-align: justify;"><span style="color: rgb(123, 12, 0);"><strong>往期精彩:</strong><strong></strong></span></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483842&idx=1&sn=d13766e818d097de075cbd02b0fe3523&chksm=ec3ba4aadb4c2dbc0928be8e451c20b1e72cdb1c7e8ca5eede70c298bc80db2783e920fa76ab&scene=21#wechat_redirect" target="_blank">如何写出整洁规范的R代码?是时候讨论一下代码规范性了</a><br></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483834&idx=1&sn=b82d9440d5b75affa66e8efc0b08116b&chksm=ec3ba4d2db4c2dc4d7b8008af97ff9cbcf1212a590add3688eb4dba7071950f8faf13cec2e43&scene=21#wechat_redirect" target="_blank">R语言也能玩ps?magick包你值得拥有</a><br></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483812&idx=1&sn=98d224398abacc7fdb45ab9be43c4137&chksm=ec3ba4ccdb4c2dda343a9365a35c4435067448e95a1c8514543707501f13aa91ac163e914680&scene=21#wechat_redirect" target="_blank">【机器学习】决策树总结|ID3 C4.5/C5.0 CHAID CART与QUEST</a><br></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483796&idx=1&sn=8d2d1bc59b577b68da32f396cdbc1239&chksm=ec3ba4fcdb4c2dea3305559857df2f1a81cbb39981c8b3d886b2683423a2ad60e2b95959ff8f&scene=21#wechat_redirect" target="_blank">R语言向量化运算:apply函数族用法心得</a><br></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483847&idx=1&sn=067d16637e43004c847a653870b27fdd&chksm=ec3ba4afdb4c2db9613326006394c11c5580741c17c3d8c07b180e649299027b7dc73f2356c9&scene=21#wechat_redirect" target="_blank">Python面向对象编程:数据封装、继承和多态</a><br></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483753&idx=1&sn=739e82d50a979325c5ece4330cdd8d7a&chksm=ec3ba401db4c2d173f556610638b77ccfd2ab64afff33918cf685f69b140af27c77a06896688&scene=21#wechat_redirect" target="_blank">[译]为什么R语言是当今最值得学习的数据科学语言</a><br></p><p style="text-align: justify;"><a href="http://mp.weixin.qq.com/s?__biz=MzI4ODY2NjYzMQ==&mid=2247483723&idx=1&sn=0847c60cc55cba9da6730dcdd51513fb&chksm=ec3ba423db4c2d356d45214c4a44ba30d70d48cbcb356d8958811fcfb44f859d7ff8edab834d&scene=21#wechat_redirect" target="_blank">Python高级特性:切片、迭代、列表生成式、生成器与迭代器</a></p><p style="text-align: center;"><span style="color: rgb(62, 62, 62);"><img src="http://mmbiz.qpic.cn/mmbiz_jpg/4lN1XOZshfdbYflMhGX1dy3d32oV6s4hicoL1WfQJvvgEaRjYVKNbGFzoUFQL0InGwVAeayEv8r6xNJoWPkD3Lw/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1"><br></span></p> </div> <div class="meta clearfix"> <div style="position: relative;" class="aw-article-vote pull-left"> <a style="font-size: 18px;" href="javascript:;" class="agree" onclick="AWS.User.article_vote($(this), 9808, 1);"><i class="icon icon-agree"></i> 推荐 <b>0</b></a> </div> <span class="pull-right more-operate"> <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a><a href="#" class="bds_mail" data-cmd="mail" title="分享到邮件分享"></a></div> <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"1","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> </span> </div> </div> <div class="mod-footer"> </div> <div class="article-license mb10 mt20 alert alert-info"> <div class="license-item license-sa"> 本文由 <a class="aw-user-name" href="https://ask.hellobi.com/people/louwill12" data-id="59597">鲁伟</a> 创作,采用 <a href="http://creativecommons.org/licenses/by-sa/3.0/cn" target="_blank" class="alert-link">知识共享署名-相同方式共享 3.0 中国大陆许可协议</a> 进行许可。<br>转载、引用前需联系作者,并署名作者且注明文章出处。 </div> <div class="license-item license-sa"> 本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。 </div> </div> </div> <!-- 文章评论 --> <div class="aw-mod"> <div class="mod-head common-head"> <h2>0 个评论</h2> </div> <div id="blog-comment-form" class="mod-body aw-feed-list"> </div> </div> <!-- end 文章评论 --> <!-- 回复编辑器 --> <div class="aw-mod aw-article-replay-box"> <a name="answer_form"></a> <p align="center">要回复文章请先<a href="https://ask.hellobi.com/account/login/">登录</a>或<a href="https://ask.hellobi.com/account/register/">注册</a></p> </div> <!-- end 回复编辑器 --> </div> </div> <!-- /.row --> </section> <!-- /.content --> </div> </div> <script type="text/javascript"> var ANSWER_EDIT_TIME = 0; jQuery(function($) { $(document).ready( function() { if($('.content-index')){ $('.content-index').stickUp(); } }); }); $(document).ready(function () { // $("#content-index-contents").pin({containerSelector: ".content-index"}); $('body').scrollspy({ target: '.content-index' }); $(".content-index a").click(function(){ var section= $(this).attr('data-index'); var offset = $("#" + section).offset(); $('body,html').animate({scrollTop:offset.top},500); }); if ($('.aw-article-vote.disabled').length) { $('.aw-article-vote.disabled a').attr('onclick', ''); } AWS.at_user_lists('#wmd-input'); AWS.Init.init_article_comment_box($('.aw-article-comment')); }); </script> <footer id="footer"> <div class="container"> <div class="row hidden-xs"> <div class="col-sm-4"> <h3>内容许可</h3> <p> 除特别说明外,用户内容均采用<a style="color: #888;" rel="license" target="_blank" href="http://creativecommons.org/licenses/by-sa/3.0/cn/">知识共享署名-相同方式共享 3.0 中国大陆许可协议</a> 进行许可 </p> </div> <div class="col-sm-2"> <h3>服务指南</h3> <ul class="site_links"> <li><a href="https://ask.hellobi.com/question/38" target="_blank">提问技巧</a></li> <li><a href="https://ask.hellobi.com/question/39" target="_blank">声望说明</a></li> <li><a href="https://ask.hellobi.com/question/5" target="_blank">使用指南</a></li> <li><a href="https://ask.hellobi.com/help/" target="_blank">帮助中心</a></li> <li><a href="https://ask.hellobi.com/corp/agreement" target="_blank">用户协议</a></li> </ul> </div> <div class="col-sm-2"> <h3>常用链接</h3> <ul class="site_links"> <li><a href="http://edu.hellobi.com" target="_blank">商业智能学院</a></li> <li><a href="https://ask.hellobi.com" target="_blank">商业智能社区</a></li> <li><a href="http://www.tianshansoft.com" target="_blank">商业智能培训</a></li> <li><a href="http://www.bijob.cn" target="_blank">BIJOB</a></li> </ul> </div> <div class="col-sm-2"> <h3>关注我们</h3> <ul class="site_links"> <li><a href="http://weibo.com/tianshansoft/" target="_blank" rel="nofollow">微博关注</a></li> <li><a href="http://list.qq.com/cgi-bin/qf_invite?id=3e83748afce7d3a22714e20b32cc8f885a0e70e49eefce57" target="_blank" rel="nofollow">邮件订阅</a></li> </ul> </div> <div class="col-sm-2"> <h3>微信关注</h3> <img style="width: 80%;" src="https://cdn.ibrand.cc/cxycbd.jpg" class="img-responsive"> </div> </div> <div class="row"> <ul class="friendly_links"> <li>友情链接:</li> <li><a href="http://www.smartbi.com.cn" target="_blank">Smartbi</a></li> <li><a href="http://www.ethinkbi.com" target="_blank">ETHINKBI</a></li> <li><a href="http://www.yonghongtech.com?utm_source=hellobi&utm_medium=corperation&utm_campaign=home&utm_content=link&utm_term=link" target="_blank">永洪科技</a></li> <li><a href="http://www.keyroads.com" target="_blank">Halo BI</a></li> <li><a href="http://www.taskctl.com" target="_blank">TASKCTL</a></li> <li><a href="http://www.powerbi.com.cn" target="_blank">奥威Power-BI</a></li> <li><a href="http://www.afenxi.com/" target="_blank" rel="nofollow" title="数据分析网-大数据资讯、观点、技术研究中心">数据分析网</a></li> <li> <a href="http://www.raqsoft.com.cn/" target="_blank">润乾软件</a> </li> </ul> </div> <div class="copyright" style="text-align: center; margin-top: 15px;"> 始于2011年 上海拓善智能科技有限公司 版权所有 | <a style="color: #888;" href="http://www.miibeian.gov.cn/" rel="nofollow" target="_blank">沪ICP备12033218号</a> | <a target="_blank" style="color: #888;" href="https://www.hellobi.com/sitemap">网站地图</a> </div> </div> </footer> <a style="display: block;" class="aw-back-top hidden-xs" href="javascript:;" onclick="$.scrollTo(1, 600, {queue:true});"><i class="icon icon-up"></i></a> <div style="display: none"> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?3b93c0177a9dcece02f1b48c41490dc5"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-42396300-5', 'auto'); ga('send', 'pageview'); </script> </div> <!-- DO NOT REMOVE --> <div id="aw-ajax-box" class="aw-ajax-box"></div> <div style="display:none;" id="__crond"> <script type="text/javascript"> $(document).ready(function () { $('#__crond').html(unescape('%3Cimg%20src%3D%22' + G_BASE_URL + '/crond/run/1714539765%22%20width%3D%221%22%20height%3D%221%22%20/%3E')); }); </script> </div> <!-- Escape time: 0.23442196846008 --><!-- / DO NOT REMOVE --> </body> </html>