怎么用r语言 as.data.frame中用gibbs sampler分析censored data

&figure&&img src=&https://pic4.zhimg.com/v2-dd350fe5c502b2481249_b.jpg& data-rawwidth=&628& data-rawheight=&394& class=&origin_image zh-lightbox-thumb& width=&628& data-original=&https://pic4.zhimg.com/v2-dd350fe5c502b2481249_r.jpg&&&/figure&&p&本文章属于&a href=&https://zhuanlan.zhihu.com/p/& class=&internal&&爬虫入门到精通系统教程&/a&第二讲&/p&&p&&br&&/p&&h2&什么是HTTP协议?&/h2&&p&引用自维基百科&/p&&blockquote&超文本传输协议(英文:HyperText Transfer Protocol,缩写:HTTP)是互联网上应用最为广泛的一种网络协议。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。通过HTTP或者HTTPS协议请求的资源由统一资源标识符(Uniform Resource Identifiers,URI)来标识。 HTTP的发展是由蒂姆·伯纳斯-李于1989年在欧洲核子研究组织(CERN)所发起。由万维网协会(World Wide Web Consortium,W3C)和互联网工程任务组(Internet Engineering Task Force,IETF)制定标准,最终发布了一系列的RFC,其中最著名的是1999年6月公布的 RFC 2616,定义了HTTP协议中现今广泛使用的一个版本——HTTP 1.1。 2014年12月,互联网工程任务组(IETF)的Hypertext Transfer Protocol Bis(httpbis)工作小组将HTTP/2标准提议递交至IESG进行讨论[1],于日被批准。[2] HTTP/2标准于2015年5月以RFC 7540正式发表,替换HTTP 1.1成为HTTP的实现标准。[3]&br&HTTP是一个客户端终端(用户)和服务器端(网站)请求和应答的标准(TCP)。通过使用网页浏览器、网络爬虫或者其它的工具,客户端发起一个HTTP请求到服务器上指定端口(默认端口为80)。我们称这个客户端为用户代理程序(user agent)。应答的服务器上存储着一些资源,比如HTML文件和图像。我们称这个应答服务器为源服务器(origin server)。在用户代理和源服务器中间可能存在多个“中间层”,比如代理服务器、网关或者隧道(tunnel)。 尽管TCP/IP协议是互联网上最流行的应用,HTTP协议中,并没有规定必须使用它或它支持的层。事实上,HTTP可以在任何互联网协议上,或其他网络上实现。HTTP假定其下层协议提供可靠的传输。因此,任何能够提供这种保证的协议都可以被其使用。因此也就是其在TCP/IP协议族使用TCP作为其传输层。 通常,由HTTP客户端发起一个请求,创建一个到服务器指定端口(默认是80端口)的TCP连接。HTTP服务器则在那个端口监听客户端的请求。一旦收到请求,服务器会向客户端返回一个状态,比如&HTTP/1.1 200 OK&,以及返回的内容,如请求的文件、错误消息、或者其它信息。&/blockquote&&h2&一个实例&/h2&&ul&&li&打开&a href=&https://zhuanlan.zhihu.com/p/& class=&internal&&爬虫从入门到精通系统教程---目录&/a& 这个网页&/li&&li&按键盘上的F12(开发者工具)&/li&&li&点击键盘上的F5刷新下网页&/li&&li&点击Network&/li&&li&点击Doc&/li&&/ul&&p&应该会看到如下界面 &/p&&figure&&img src=&http://pic1.zhimg.com/v2-f0bc7f49da2dc79e80bfa10_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1919& data-rawheight=&689& class=&origin_image zh-lightbox-thumb& width=&1919& data-original=&http://pic1.zhimg.com/v2-f0bc7f49da2dc79e80bfa10_r.jpg&&&/figure&&p&&br&&/p&&p&然后我们点击&/p&&div class=&highlight&&&pre&&code class=&language-python&&&span&&/span&&span class=&mi&&&/span&
&/code&&/pre&&/div&&p&应该会看到如下界面 &/p&&figure&&img src=&http://pic2.zhimg.com/v2-0d832df33d7d3a89570cb5_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1919& data-rawheight=&801& class=&origin_image zh-lightbox-thumb& width=&1919& data-original=&http://pic2.zhimg.com/v2-0d832df33d7d3a89570cb5_r.jpg&&&/figure&&p&&br&&/p&&h2&General&/h2&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Request URL:https://zhuanlan.zhihu.com/p/ (爬虫会用到)
&/code&&/pre&&/div&&p&这个对应HTTP协议中的&b&统一资源定位符&/b&也就是我们打开的网址&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Request Method:GET(爬虫会用到)
&/code&&/pre&&/div&&p&这个对应HTTP协议中的&b&请求方法&/b&,我们这次用的是GET&/p&&p&请求方法有以下这些,常用的是&b&GET&/b&,&b&POST&/b&&/p&&ul&&li&GET:向指定的资源发出“显示”请求。使用GET方法应该只用在读取数据,而不应当被用于产生“副作用”的操作中,例如在Web Application中。其中一个原因是GET可能会被网络蜘蛛等随意访问。参见安全方法&/li&&li&POST:向指定资源提交数据,请求服务器进行处理(例如提交表单或者上传文件)。数据被包含在请求本文中。这个请求可能会创建新的资源或修改现有资源,或二者皆有。&/li&&li&OPTIONS:这个方法可使服务器传回该资源所支持的所有HTTP请求方法。用'*'来代替资源名称,向Web服务器发送OPTIONS请求,可以测试服务器功能是否正常运作。&/li&&li&HEAD:与GET方法一样,都是向服务器发出指定资源的请求。只不过服务器将不传回资源的本文部分。它的好处在于,使用这个方法可以在不必传输全部内容的情况下,就可以获取其中“关于该资源的信息”(元信息或称元数据)。&/li&&li&PUT:向指定资源位置上传其最新内容。&/li&&li&DELETE:请求服务器删除Request-URI所标识的资源。&/li&&li&TRACE:回显服务器收到的请求,主要用于测试或诊断。&/li&&li&CONNECT:HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。通常用于SSL加密服务器的链接(经由非加密的HTTP代理服务器)。&/li&&/ul&&div class=&highlight&&&pre&&code class=&language-python&&&span&&/span&&span class=&n&&Status&/span& &span class=&n&&Code&/span&&span class=&p&&:&/span&&span class=&mi&&200&/span& &span class=&n&&OK&/span&&span class=&err&&(爬虫会用到)&/span&
&/code&&/pre&&/div&&p&这个对应HTTP协议中的&b&状态码&/b&,我们这次返回的是200 OK、&/p&&blockquote&所有HTTP响应的第一行都是状态行,依次是当前HTTP版本号,3位数字组成的状态代码,以及描述状态的短语,彼此由空格分隔。 状态代码的第一个数字代表当前响应的类型:&/blockquote&&ul&&li&1xx消息——请求已被服务器接收,继续处理&/li&&li&2xx成功——请求已成功被服务器接收、理解、并接受&/li&&li&3xx重定向——需要后续操作才能完成这一请求&/li&&li&4xx请求错误——请求含有词法错误或者无法被执行&/li&&li&5xx服务器错误——服务器在处理某个正确请求时发生错误&/li&&/ul&&blockquote&常见状态代码、状态描述、说明:&/blockquote&&ul&&li&200 OK //请求成功&/li&&li&400 Bad Request //客户端请求有语法错误,不能被服务器所理解&/li&&li&401 Unauthorized //请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用&/li&&li&403 Forbidden //服务器收到请求,但是拒绝提供服务&/li&&li&404 Not Found //请求资源不存在,eg:输入了错误的URL&/li&&li&500 Internal Server Error //服务器发生不可预期的错误&/li&&li&503 Server Unavailable //服务器当前不能处理客户端的请求,一段时间后可能恢复正常&/li&&/ul&&h2&Requests Headers(请求头)&/h2&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Accept:text/html,application/xhtml+xml,application/q=0.9,image/webp,*/*;q=0.8(爬虫会用到)
&/code&&/pre&&/div&&blockquote&Accept请求报头域用于指定客户端接受哪些类型的信息。eg:Accept:image/gif,表明客户端希望接受GIF图象格式的资源;Accept:text/html,表明客户端希望接受html文本。&/blockquote&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Accept-Encoding:gzip, deflate, sdch, br
&/code&&/pre&&/div&&blockquote&Accept-Encoding请求报头域类似于Accept,但是它是用于指定可接受的内容编码。eg:Accept-Encoding:gzip.deflate.如果请求消息中没有设置这个域服务器假定客户端对各种内容编码都可以接受。&/blockquote&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Accept-Language:zh-CN,q=0.8
&/code&&/pre&&/div&&blockquote&Accept-Language请求报头域类似于Accept,但是它是用于指定一种自然语言。eg:Accept-Language:zh-cn.如果请求消息中没有设置这个报头域,服务器假定客户端对各种语言都可以接受&/blockquote&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Cache-Control:no-cache
&/code&&/pre&&/div&&p&Cache-Control 是用来控制网页的缓存,详细可以&a href=&http://link.zhihu.com/?target=http%3A//baike.baidu.com/link%3Furl%3DOiJmCPnBNa2iTR8oSQlLircjkN0f_jSkaDI3uv88SYwx9JOl3q8PrlRJMoq87hE4ZSyUfe8n3byeogqZcztpEEkUjaLBJwpuXm_AcLw740_& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Cache-control_百度百科&/a&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Connection:keep-alive
&/code&&/pre&&/div&&blockquote&HTTP持久连接(HTTP persistent connection,也称作HTTP keep-alive或HTTP connection reuse)是使用同一个TCP连接来发送和接收多个HTTP请求/应答,而不是为每一个新的请求/应答打开新的连接的方法。 详情介绍请参考&a href=&http://link.zhihu.com/?target=https%3A//zh.wikipedia.org/wiki/HTTP%25E6%258C%%25B9%%25BF%259E%25E6%258E%25A5& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&HTTP持久连接&/a&&/blockquote&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Cookie:d_c0=&AACAWNtZswqPTnJ8dFXqaygiq82ekPD5_-xxxx(爬虫会用到)
&/code&&/pre&&/div&&p&&br&&/p&&blockquote&Cookie(复数形态Cookies),中文名称为“小型文本文件”或“小甜饼”[1],指某些网站为了&b&辨别用户身份而储存在用户本地终端&/b&(Client Side)上的数据(通常经过加密)。定义于RFC2109。是网景公司的前雇员卢·蒙特利在1993年3月的发明[2]。详情介绍请参考&a href=&http://link.zhihu.com/?target=https%3A//zh.wikipedia.org/wiki/Cookie& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Cookie&/a&&/blockquote&&p&举个例子,当我登录知乎后,知乎会给我一个cookie,然后我在以后的一段时间内,每次打开知乎,都不需要重新登录。这是因为浏览器每次都会把我之前存储的cookie带上。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Host:zhuanlan.zhihu.com
&/code&&/pre&&/div&&p&当前请求网址的请求域&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36(爬虫会用到)
&/code&&/pre&&/div&&p&用户是通过什么工具来请求的,(因为我用的Google浏览器,所以显示的是Chrome)&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Referer:https://www.zhihu.com/people/pa-chong-21/activities(爬虫会用到)
&/code&&/pre&&/div&&p&是通过哪个页面到当前页面的(也就是上一个页面是什么?当前截图里面没有)&/p&&p&举个例子,当我是通过百度搜索页面点到当前页面的,那么Referer就是百度搜索页&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&If-Modified-Since:Wed, 15 Feb :13 GMT
If-None-Match:W/&58a41be5-190aa&
Last-Modified:Wed, 15 Feb :13 GMT
ETag:&58a41be5-190aa&
&/code&&/pre&&/div&&p&这4个一般静态页面会用到 If-Modified-Since,If-None-Match这两个是请求头,ETag,Last-Modified是返回头(服务器返回的)&/p&&p&如果If-Modified-Since的值和Last-Modified相等 则表明当前请求的内容没有变动,服务器返回 &/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Status Code:304 Not Modified
&/code&&/pre&&/div&&p&If-None-Match和ETag 同理&/p&&figure&&img src=&http://pic4.zhimg.com/v2-f139aa96366ebdb3b4118033_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&885& data-rawheight=&554& class=&origin_image zh-lightbox-thumb& width=&885& data-original=&http://pic4.zhimg.com/v2-f139aa96366ebdb3b4118033_r.jpg&&&/figure&&p&&br&&/p&&h2&总结&/h2&&p&看完本篇文章后,你应该要&/p&&ul&&li&大概了解什么是HTTP协议&/li&&li&HTTP常见请求方法有哪几种?&/li&&li&HTTP常见状态码有哪些?&/li&&li&HTTP请求头中,大概了解Accept,Cookie,User-Agent,Referer是干啥的?&/li&&/ul&&p&&br&&/p&&p&&b&欢迎关注本人的微信公众号获取更多Python爬虫相关的内容&/b&&/p&&p&&b&(可以直接搜索「Python爬虫分享」)&/b&&/p&
本文章属于第二讲 什么是HTTP协议?引用自维基百科超文本传输协议(英文:HyperText Transfer Protocol,缩写:HTTP)是互联网上应用最为广泛的一种网络协议。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。通过HTTP或…
&figure&&img src=&https://pic1.zhimg.com/v2-3d0d1fad87a9f6319a0e_b.jpg& data-rawwidth=&1024& data-rawheight=&576& class=&origin_image zh-lightbox-thumb& width=&1024& data-original=&https://pic1.zhimg.com/v2-3d0d1fad87a9f6319a0e_r.jpg&&&/figure&&h2&&b&说在前面&/b&&/h2&如果读过了上一篇文章,应该对Rcurl和XML包进行爬虫有了一定得了解。实际上,这个组合虽然功能强大,但是经常会出一点意想不到的小问题。这篇文章我将介绍更便捷的Rvest包真正的快速爬取想要的数据。&h2&&b&主要内容&/b&&/h2&&p&
还是以上篇文章的&a href=&http://link.zhihu.com/?target=https%3A//book.douban.com/top250%3Ficn%3Dindex-book250-all& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&豆瓣图书 Top250&/a&为例,我们只需要以下几行代码就可以实现与上文一样的效果:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&library(rvest)
web&-read_html(&https://book.douban.com/top250?icn=index-book250-all&,encoding=&UTF-8&)
position&-web %&% html_nodes(&p.pl&) %&% html_text()
&/code&&/pre&&/div&&p&逐行解读一下。&/p&&p&&b&第一行是加载Rvest包。&/b&&/p&&p&&b&第二行是用read_html函数读取网页信息&/b&(类似Rcurl里的getURL),在这个函数里只需写清楚网址和编码(一般就是UTF-8)即可。&/p&&p&&b&第三行是获取节点信息&/b&。用%&%符号进行层级划分。web就是之前存储网页信息的变量,所以我们从这里开始,然后html_nodes()函数获取网页里的相应节点。在下面代码里我简单的重现了原网页里的一个层级结构。可以看到,实际上我们要爬取的信息在25个class属性为pl的&p&标签里的文本。&/p&&br&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&&p class=pl&
[清] 曹雪芹 著 / 人民文学出版社 / 1996-12 / 59.70元
&/code&&/pre&&/div&&p&而对于这样的结构,在htmlnodes()函数里的写法就是简单的 &p.pl&,其中“.”表示class属性的值,如果是id属性则用“#”,如果大家学过CSS选择器就很好理解了,是完全一致的。&br&&/p&&p&最后我们用html_text()函数表示获取文本信息,否则返回的是整个&p&标签。总体上用以下一行代码就可以实现:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&position&-web %&% html_nodes(&p.pl&) %&% html_text()
&/code&&/pre&&/div&&p&比较与XML获取节点的方法(如下行代码),其实二者是异曲同工的,只不过将“/”分隔换为了“%&%”,同时个别写法有些许调整。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&node&-getNodeSet(pagetree, &//p[@class='pl']/text()&)
&/code&&/pre&&/div&&p&最终如果我们打印出这个变量的内容,就会发现和上篇文章中的爬取内容是一致的:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& position
[1] &[美] 卡勒德·胡赛尼 / 李继宏 / 上海人民出版社 / 2006-5 / 29.00元&
[2] &[法] 圣埃克苏佩里 / 马振聘 / 人民文学出版社 / 2003-8 / 22.00元&
[3] &钱锺书 / 人民文学出版社 / 1991-2 / 19.00&
[4] &余华 / 南海出版公司 / 1998-5 / 12.00元&
[5] &[日] 东野圭吾 / 刘姿君 / 南海出版公司 / 2008-9 / 29.80元&
[6] &[日] 村上春树 / 林少华 / 上海译文出版社 / 2001-2 / 18.80元&
[7] &(日)东野圭吾 / 李盈春 / 南海出版公司 / 2014-5 / 39.50元&
[8] &[捷克] 米兰·昆德拉 / 许钧 / 上海译文出版社 / 2003-7 / 23.00元&
[9] &[清] 曹雪芹 著 / 人民文学出版社 / 1996-12 / 59.70元&
[10] &刘慈欣 / 重庆出版社 / 2008-1 / 23.00&
[11] &郭敬明 / 春风文艺出版社 / 2003-11 / 20.00元&
[12] &[美] 丹·布朗 / 朱振武 / 上海人民出版社 / 2004-2 / 28.00元&
[13] &[日] 东野圭吾 / 刘子倩 / 南海出版公司 / 2008-9 / 28.00&
[14] &韩寒 / 国际文化出版公司 / 2010-9 / 25.00元&
[15] &柴静 / 广西师范大学出版社 /
/ 39.80元&
[16] &顾漫 / 朝华出版社 / 2007-4 / 15.00元&
[17] &[英] 夏洛蒂·勃朗特 / 世界图书出版公司 / 2003-11 / 18.00元&
[18] &路遥 / 人民文学出版社 / 2005-1 / 64.00元&
[19] &[英] J. K. 罗琳 / 苏农 / 人民文学出版社 / 2000-9 / 19.50元&
[20] &[哥伦比亚] 加西亚·马尔克斯 / 范晔 / 南海出版公司 / 2011-6 / 39.50元&
[21] &[美国] 玛格丽特·米切尔 / 李美华 / 译林出版社 / 2000-9 / 40.00元&
[22] &李可 / 陕西师范大学出版社 / 2007-9 / 26.00元&
[23] &韩寒 / 作家出版社 / 2000-5 / 16.00&
[24] &刘瑜 / 上海三联书店 / 2010-1 / 25.00元&
[25] &张爱玲 / 花城出版社 /
&/code&&/pre&&/div&&p&想要学习更多,我们可以在Rstudio里的命令行输入如下代码查询html_nodes()函数的相关用法:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&?html_nodes
&/code&&/pre&&/div&&p&Rvest这个包的说明文档里给出了一些其他例子:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&ateam &- read_html(&http://www.boxofficemojo.com/movies/?id=ateam.htm&)
ateam %&% html_nodes(&center&) %&% html_nodes(&td&)
ateam %&% html_nodes(&center&) %&% html_nodes(&font&)
library(magrittr)
ateam %&% html_nodes(&table&) %&% extract2(1) %&% html_nodes(&img&)
ateam %&% html_nodes(&table&) %&% `[[`(1) %&% html_nodes(&img&)
ateam %&% html_nodes(&table&) %&% `[`(1:2) %&% html_nodes(&img&)
ateam %&% html_nodes(&table&) %&% extract(1:2) %&% html_nodes(&img&)
&/code&&/pre&&/div&&p&下面也一并讲解一下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&ateam &- read_html(&http://www.boxofficemojo.com/movies/?id=ateam.htm&)
&/code&&/pre&&/div&&p&首先,所有的例子都是基于同一个网站,我们把这个网站存储在ateam变量里。&/p&&p&然后下面两行代码分别获取了ateam这个网页里&center&标签里&td&的全部内容和&center&标签里&font&的全部内容&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&ateam %&% html_nodes(&center&) %&% html_nodes(&td&)
ateam %&% html_nodes(&center&) %&% html_nodes(&font&)
&/code&&/pre&&/div&&p&运行结果如下,可见&center&标签下有7个&td&标签,一个&font&标签:&/p&&br&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&{xml_nodeset (7)}
[1] &td align=&center& colspan=&2&&\n
&font size=&4&&Domestic Total Gross: &b&$77,222, ...
[2] &td valign=&top&&Distributor: &b&&a href=&/studio/chart/?studio=fox.htm&&Fox&/a&&/b ...
[3] &td valign=&top&&Release Date: &b&&nobr&&a href=&/schedule/?view=bydate&release ...
[4] &td valign=&top&&Genre: &b&Action&/b&&/td&
[5] &td valign=&top&&Runtime: &b&1 hrs. 57 min.&/b&&/td&
[6] &td valign=&top&&MPAA Rating: &b&PG-13&/b&&/td&
[7] &td valign=&top&&Production Budget: &b&$110 million&/b&&/td&
{xml_nodeset (1)}
[1] &font size=&4&&Domestic Total Gross: &b&$77,222,099&/b&&/font&
&/code&&/pre&&/div&&p&接着官方例子中还给出了获取特定序位的html标签的方法,用到了magrittr包里的extract2函数:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&library(magrittr)
ateam %&% html_nodes(&table&) %&% extract2(1) %&% html_nodes(&img&)
ateam %&% html_nodes(&table&) %&% `[[`(1) %&% html_nodes(&img&)
&/code&&/pre&&/div&&p&上面两行代码都可以获得该网页中第一个&table&标签(由extract2(1)或`[[`(1)获取)中的所有&img&标签里的内容,运行结果如下:&/p&&br&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&{xml_nodeset (6)}
[1] &img src=&https://images-na.ssl-images-amazon.com/images/M/MV5BMTc4ODc4NTQ1N15BMl5B ...
[2] &img src=&http://www.assoc-amazon.com/e/ir?t=boxofficemojo-20&l=as2&o=1&amp ...
[3] &img src=&http://www.assoc-amazon.com/e/ir?t=boxofficemojo-20&l=as2&o=1&amp ...
[4] &img src=&/img/misc/bom_logo1.png& width=&245& height=&56& alt=&Box Office Mojo&/&
[5] &img src=&/img/misc/IMDbSm.png& width=&34& height=&16& alt=&IMDb& valign=&middle&/&
[6] &img src=&http://b.scorecardresearch.com/p?c1=2&c2=6034961&cv=2.0&cj=1&/&
&/code&&/pre&&/div&&p&同理我们也可以获得网页里前两个&table&标签储存的所有&img&标签里的内容:&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&ateam %&% html_nodes(&table&) %&% `[`(1:2) %&% html_nodes(&img&)
ateam %&% html_nodes(&table&) %&% extract(1:2) %&% html_nodes(&img&)
&/code&&/pre&&/div&&p&本篇文章就到此为止了,之后我将继续讲解关于正则以及R中stringr包的相关内容,对获取的字符串进行进一步的处理操作。&/p&&h2&&b&结语&/b&&/h2&&p&更多内容请关注我的专栏:&a href=&https://zhuanlan.zhihu.com/rdatamining& class=&internal&&R语言与数据挖掘 - 知乎专栏&/a&&/p&&p&或关注我本人知乎主页:&a href=&https://www.zhihu.com/people/wen-yi-yang-81& class=&internal&&温如&/a&&/p&
说在前面如果读过了上一篇文章,应该对Rcurl和XML包进行爬虫有了一定得了解。实际上,这个组合虽然功能强大,但是经常会出一点意想不到的小问题。这篇文章我将介绍更便捷的Rvest包真正的快速爬取想要的数据。主要内容 还是以上篇文章的为例…
&figure&&img src=&https://pic3.zhimg.com/v2-cda7e8f6b0fd869b6fcf5f169e21f027_b.jpg& data-rawwidth=&1000& data-rawheight=&667& class=&origin_image zh-lightbox-thumb& width=&1000& data-original=&https://pic3.zhimg.com/v2-cda7e8f6b0fd869b6fcf5f169e21f027_r.jpg&&&/figure&&h2&&b&说在前面&/b&&/h2&&p&
本来本系列文章是不涉及爬虫内容的,但是由于很多人回复以及私信我有这方面的需求,所以我特意多写一篇文章,介绍R语言爬虫的知识。&/p&&h2&&b&主要内容&/b&&/h2&&p&
爬虫是一种利用代码(例如:R code或Python code)模拟浏览器访问(下载)页面并根据HTML结构筛选获取所需信息的一种工具。在R里面我们通常用Rcurl包实现前一半的功能(模拟浏览器访问页面),用XML包完成后一半功能(通过HTML树结构筛选提取信息)。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&install.packages(&RCurl&)
install.packages(&XML&)
library(RCurl)
library(XML)
&/code&&/pre&&/div&&p&
下面就用一个实例进行讲解,爬取豆瓣读书top250清单的部分信息。&/p&&p&&b&
第一步,模拟浏览器行为&/b&&/p&&br&&p&若想用R语言模拟浏览器行为,就必须伪装报头。实际上,当我们用浏览器访问一个网页的时候,浏览器会像网页服务器发送一些指令。以COS网站为例:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&GET / HTTP/1.1
Host: cos.name
User-Agent: Mozilla/5.0 (W U; Windows NT 5.1; zh-CN; rv:1.9.1.6)
Accept: text/html,application/xhtml+xml,application/q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip,deflate
Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
&/code&&/pre&&/div&&p&
所以为了伪装成一个浏览器,我们必须让R语言像网站发送以上指令,这就叫做我伪装报头,代码如下,可直接copy。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&myHttpheader &- c(
&User-Agent&=&Mozilla/5.0 (W U; Windows NT 5.1; zh-CN; rv:1.9.1.6) &,
&Accept&=&text/html,application/xhtml+xml,application/q=0.9,*/*;q=0.8&,
&Accept-Language&=&en-us&,
&Connection&=&keep-alive&,
&Accept-Charset&=&GB2312,utf-8;q=0.7,*;q=0.7&
&/code&&/pre&&/div&&p&
至此,报头信息就储存在了myHttpheader这个变量中了。&/p&&p&&b&
第二步,就是模拟访问页面&/b&&/p&&p&这个过程其实就是把指定的网页临时下载下来。两行代码就可以实现。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&url &- &https://book.douban.com/top250?icn=index-book250-all&
webpage &- getURL(url,httpheader=myHttpheader)
&/code&&/pre&&/div&&p&
如上面代码所示,我们将爬取url里储存的网页地址&a href=&http://link.zhihu.com/?target=https%3A//book.douban.com/top250%3Ficn%3Dindex-book250-all& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&豆瓣图书 Top250&/a&,读者使用的时候可以自行替换其中地址为自己想要爬取的地址。&/p&&p&
在RCurl的目前版本中,有170多个cURL系统参数可以设置,具体可以用&/p&&p&names(getCurlOptionsConstants())查看一下,各个参数的详细说明则可以参照libcurl的官方&a href=&http://link.zhihu.com/?target=http%3A//curl.haxx.se/libcurl/c/curl_easy_setopt.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&说明文档&/a&。&/p&&p&
下载以后我们可以在命令行输入webpage查看下载的页面(HTML代码):&/p&&p&&b&
第三步,整理HTML结构。&/b&&/p&&p&接下来,就是使用XML中的htmlTreeParse函数解析刚才得到的webpage变量(其中储存了HTML所爬取网页的代码)生成标准的HTML树形结构并赋值给pagetree变量。之后便可在XML中对该变量进行各种操作了。&/p&&br&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&pagetree &- htmlTreeParse(webpage,encoding=&GB2312&, error=function(...){}, useInternalNodes = TRUE,trim=TRUE)
#注意encoding
&/code&&/pre&&/div&&p&&b&第四步:节点定位&/b&&/p&&p&在这里我们需要一点HTML的基础知识。HTML下的代码实际上是一个树级结构,是不同标签的层级嵌套。每一个标签以&x&开始,以&/x&结束。举个例子:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&&body&
&div class=&first&&
&a href=&www.baidu.com& title=&百度&&链接1&/a&
&div class=&first&&
&a href=&www.sina.com& title=&新浪&&链接2&/a&
&/code&&/pre&&/div&&p&&body&与&/body&之间的内容为网页的正文部分,如果我们想获取两个&a&标签中的正文(“链接1”,“链接2”),可以利用如下代码进行定位,其中text()代表的是获取标签内的文本。乍一看,是不是和文件路径很像?&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span& ul/li/div/a/text()
&/code&&/pre&&/div&&p&此外,我们也可以用利用两个&div&具有相同的class属性值直接从&div&开始定位,也即&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&div[@class='first']/a/text()
&/code&&/pre&&/div&&p&这两个写法在XML包中都是适用的。&/p&&p&由于不是主要内容,关于HTML更多的知识在此不多赘述,详细可自行学习HTML与CSS相关知识,此乃爬虫之基础。&/p&&p&我们一般会利用chrome浏览器右键-&查看源代码,也可以对想要查看的内容点击右键-&检查,然后就会看到如下的界面:&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-e8d4cf1bb81c3e439690_b.jpg& data-rawwidth=&1577& data-rawheight=&703& class=&origin_image zh-lightbox-thumb& width=&1577& data-original=&https://pic1.zhimg.com/v2-e8d4cf1bb81c3e439690_r.jpg&&&/figure&这时候我们如果右键卡勒德胡塞尼那一行,就可以鼠标右键-&copy-&selector或Xpath直接复制相应的层级定位。需要注意的是,我们还需将复制来的定位代码更换成XML包所能识别的格式。比如用属性值用单引号,“//”表示所有该类型节点等。&/p&&br&&p&下面则重点给出了XML里常用的节点定位方法与代码,可以作为参考:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&getNodeSet(doc,'/bookstore/book[1]')
# 选取属于 bookstore 子元素的最后一个 book 元素。
getNodeSet(doc,'/bookstore/book[last()]')
# 选取最前面的两个属于 bookstore 元素的子元素的 book 元素
getNodeSet(doc,'/bookstore/book[position()&3]')
# 选取所有拥有名为 lang 的属性的 title 元素。
getNodeSet(doc,'//title[@lang]')
#选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性
getNodeSet(doc,&//title[@lang='eng']&)
# 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
getNodeSet(doc,&/bookstore/book[price&35.00]&)
# 选取 bookstore 元素中的 book 元素的所有 title 元素,且 price 元素的值须大于 35.00。
getNodeSet(doc,&/bookstore/book[price&35.00]/title&)
# 选取 book 元素的所有 title 和 price 元素
getNodeSet(doc,&//book/title | //book/price&)
# 选取文档中的所有 title 和 price 元素
getNodeSet(doc,&//title | //price&)
# 选取 bookstore 元素的所有子元素
getNodeSet(doc,&/bookstore/*&)
# 选取所有带有属性的 title 元素
getNodeSet(doc,&//title[@*]&)
# 选择所有属性lang的值
unlist(getNodeSet(doc,&//title/@lang&),use.names = FALSE)
# title结点下的所有文本
getNodeSet(doc,&//title/text()&)
&/code&&/pre&&/div&&p&&b&在此例中,我们用如下代码(XML包里的getNodeSet函数)定位每本书的详细信息,其中sapply函数则是为了将xmlvalue类型的数据集合转化为R语言中常见的向量形式,方便处理:&/b&&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&node&-getNodeSet(pagetree, &//p[@class='pl']/text()&)
info&-sapply(node,xmlValue)
&/code&&/pre&&/div&&p&由于第一页只储存了25本书的信息,所以最终得到的向量内容如下所示:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span& [1] &[美] 卡勒德·胡赛尼 / 李继宏 / 上海人民出版社 / 2006-5 / 29.00元&
[2] &[法] 圣埃克苏佩里 / 马振聘 / 人民文学出版社 / 2003-8 / 22.00元&
[3] &钱锺书 / 人民文学出版社 / 1991-2 / 19.00&
[4] &余华 / 南海出版公司 / 1998-5 / 12.00元&
[5] &[日] 东野圭吾 / 刘姿君 / 南海出版公司 / 2008-9 / 29.80元&
[6] &[日] 村上春树 / 林少华 / 上海译文出版社 / 2001-2 / 18.80元&
[7] &(日)东野圭吾 / 李盈春 / 南海出版公司 / 2014-5 / 39.50元&
[8] &[捷克] 米兰·昆德拉 / 许钧 / 上海译文出版社 / 2003-7 / 23.00元&
[9] &[清] 曹雪芹 著 / 人民文学出版社 / 1996-12 / 59.70元&
[10] &刘慈欣 / 重庆出版社 / 2008-1 / 23.00&
[11] &郭敬明 / 春风文艺出版社 / 2003-11 / 20.00元&
[12] &[美] 丹·布朗 / 朱振武 / 上海人民出版社 / 2004-2 / 28.00元&
[13] &[日] 东野圭吾 / 刘子倩 / 南海出版公司 / 2008-9 / 28.00&
[14] &韩寒 / 国际文化出版公司 / 2010-9 / 25.00元&
[15] &柴静 / 广西师范大学出版社 /
/ 39.80元&
[16] &顾漫 / 朝华出版社 / 2007-4 / 15.00元&
[17] &[英] 夏洛蒂·勃朗特 / 世界图书出版公司 / 2003-11 / 18.00元&
[18] &路遥 / 人民文学出版社 / 2005-1 / 64.00元&
[19] &[英] J. K. 罗琳 / 苏农 / 人民文学出版社 / 2000-9 / 19.50元&
[20] &[哥伦比亚] 加西亚·马尔克斯 / 范晔 / 南海出版公司 / 2011-6 / 39.50元&
[21] &[美国] 玛格丽特·米切尔 / 李美华 / 译林出版社 / 2000-9 / 40.00元&
[22] &李可 / 陕西师范大学出版社 / 2007-9 / 26.00元&
[23] &韩寒 / 作家出版社 / 2000-5 / 16.00&
[24] &刘瑜 / 上海三联书店 / 2010-1 / 25.00元&
[25] &张爱玲 / 花城出版社 /
&/code&&/pre&&/div&&p&当然我们还可以爬取&a&标签的title属性值获取每本书的名字以及通过其他方法爬取其他信息,读者可以充分自行尝试。&/p&&p&最后,如果遇到了中文乱码,可以用如下函数进行调整,其中text是所需转为中文的乱码文本:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&iconv(text,&UTF-8&)
&/code&&/pre&&/div&&p&&b&本文章只是讲述了Rcurl包所涉及的爬虫的基本用法。需要说明的是,更为复杂的爬虫还会涉及模拟登陆,ajax等知识,R语言中也还有Rvest,Rjson等相关包。期待读者自行探索,非基础知识,故在这里不做进一步介绍。&/b&&br&&/p&&p&&b&本文章所涉及的最终完整代码如下所示:&/b&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&install.packages(&RCurl&)
install.packages(&XML&)
library(RCurl)
library(XML)
myHttpheader &- c(
&User-Agent&=&Mozilla/5.0 (W U; Windows NT 5.1; zh-CN; rv:1.9.1.6) &,
&Accept&=&text/html,application/xhtml+xml,application/q=0.9,*/*;q=0.8&,
&Accept-Language&=&en-us&,
&Connection&=&keep-alive&,
&Accept-Charset&=&GB2312,utf-8;q=0.7,*;q=0.7&)
url &- &豆瓣图书 Top250&
webpage &- getURL(url,httpheader=myHttpheader,.encoding=&gb2312&)
pagetree &- htmlTreeParse(webpage,encoding=&GB2312&, error=function(...){}, useInternalNodes = TRUE,trim=TRUE)
node&-getNodeSet(pagetree, &//p[@class='pl']/text()&)
info&-sapply(node,xmlValue)
&/code&&/pre&&/div&&h2&&b&结语&/b&&/h2&&p&更多内容请关注我的专栏:&a href=&https://zhuanlan.zhihu.com/rdatamining& class=&internal&&R语言与数据挖掘 - 知乎专栏&/a&&/p&&p&或者关注我的知乎账号:&a href=&https://www.zhihu.com/people/wen-yi-yang-81& class=&internal&&温如&/a&&/p&
说在前面 本来本系列文章是不涉及爬虫内容的,但是由于很多人回复以及私信我有这方面的需求,所以我特意多写一篇文章,介绍R语言爬虫的知识。主要内容 爬虫是一种利用代码(例如:R code或Python code)模拟浏览器访问(下载)页面并根据HTML结构筛选获取所…
&figure&&img src=&https://pic2.zhimg.com/v2-bead4c7d7b70a78eb06d_b.jpg& data-rawwidth=&1054& data-rawheight=&587& class=&origin_image zh-lightbox-thumb& width=&1054& data-original=&https://pic2.zhimg.com/v2-bead4c7d7b70a78eb06d_r.jpg&&&/figure&&p&这一篇涉及到如何在网页请求环节使用多进程任务处理功能,因为网页请求涉及到两个重要问题:一是多进程的并发操作会面临更大的反爬风险,所以面临更严峻的反爬风险,二是抓取网页数据需要获取返回值,而且这些返回值需要汇集成一个关系表(数据框)(区别于上一篇中的二进制文件下载,文件下载仅仅执行语句块命令即可,无需收集返回值)。&/p&&p&R语言使用RCurl+XML,Python使用urllib+lxml。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&library(&RCurl&)
library(&XML&)
library(&magrittr&)
&/code&&/pre&&/div&&p&&b&方案1——自建显式循环:&/b&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Getjobs &- function(){
fullinfo &- data.frame()
headers &- c(&Referer&=&https://www.hellobi.com/jobs/search&,
&User-Agent&=&Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36&
d &- debugGatherer()
handle &- getCurlHandle(debugfunction=d$update,followlocation=TRUE,cookiefile=&&,verbose = TRUE)
while (i & 11){
url &- sprintf(&https://www.hellobi.com/jobs/search?page=%d&,i)
tryCatch({
&- getURL(url,.opts=list(httpheader=headers),.encoding=&utf-8&,curl=handle) %&% htmlParse()
&- content %&% xpathSApply(.,&//div[@class='job_item_middle pull-left']/h4/a&,xmlValue)
&- content %&% xpathSApply(.,&//div[@class='job_item_middle pull-left']/h4/a&,xmlGetAttr,&href&)
&- content %&% xpathSApply(.,&//div[@class='job_item_middle pull-left']/h5&,xmlValue,trim = TRUE)
job_salary &- content %&% xpathSApply(.,&//div[@class='job_item-right pull-right']/h4&,xmlValue,trim = TRUE)
job_origin &- content %&% xpathSApply(.,&//div[@class='job_item-right pull-right']/h5&,xmlValue,trim = TRUE)
data.frame(job_item,job_links,job_info,job_salary,job_origin)
&- rbind(fullinfo,myreslut)
cat(sprintf(&第【%d】页已抓取完毕!&,i),sep = &\n&)
},error = function(e){
cat(sprintf(&第【%d】页抓取失败!&,i),sep = &\n&)
cat(&all page is OK!!!&)
return (fullinfo)
system.time(mydata1 &- Getjobs())
&/code&&/pre&&/div&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic3.zhimg.com/v2-c4ed8b5b6cc98d75e05b3_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&544& data-rawheight=&384& class=&origin_image zh-lightbox-thumb& width=&544& data-original=&https://pic3.zhimg.com/v2-c4ed8b5b6cc98d75e05b3_r.jpg&&&/figure&&p&&br&&/p&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-366ac097a1bfa_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1253& data-rawheight=&640& class=&origin_image zh-lightbox-thumb& width=&1253& data-original=&https://pic1.zhimg.com/v2-366ac097a1bfa_r.jpg&&&/figure&&p&&br&&/p&&p&整个过程耗时11.03秒。&/p&&p&&b&方案2——使用向量化函数:&/b&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&Getjobs &- function(i){
fullinfo &- data.frame()
headers &- c(&Referer&=&https://www.hellobi.com/jobs/search&,
&User-Agent&=&Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36&
d &- debugGatherer()
handle &- getCurlHandle(debugfunction=d$update,followlocation=TRUE,cookiefile=&&,verbose = TRUE)
url &- sprintf(&https://www.hellobi.com/jobs/search?page=%d&,i)
&- getURL(url,.opts=list(httpheader=headers),.encoding=&utf-8&,curl=handle) %&% htmlParse()
&- content %&% xpathSApply(.,&//div[@class='job_item_middle pull-left']/h4/a&,xmlValue)
&- content %&% xpathSApply(.,&//div[@class='job_item_middle pull-left']/h4/a&,xmlGetAttr,&href&)
&- content %&% xpathSApply(.,&//div[@class='job_item_middle pull-left']/h5&,xmlValue,trim = TRUE)
job_salary &- content %&% xpathSApply(.,&//div[@class='job_item-right pull-right']/h4&,xmlValue,trim = TRUE)
job_origin &- content %&% xpathSApply(.,&//div[@class='job_item-right pull-right']/h5&,xmlValue,trim = TRUE)
data.frame(job_item,job_links,job_info,job_salary,job_origin) %&% return()
system.time(mydata &- plyr::ldply(1:10,Getjobs,.progress = &text&))
&/code&&/pre&&/div&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic3.zhimg.com/v2-615caffd86123ed_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1280& data-rawheight=&729& class=&origin_image zh-lightbox-thumb& width=&1280& data-original=&https://pic3.zhimg.com/v2-615caffd86123ed_r.jpg&&&/figure&&p&&br&&/p&&p&整个过程耗时9.07m。&/p&&p&&b&方案3——使用多进程包:&/b&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&system.time({
library(&doParallel&)
library(&foreach&)
cl&-makeCluster(4)
registerDoParallel(cl)
mydata2 &- foreach(i=1:10,
.combine=rbind,
.packages = c(&RCurl&, &XML&,&magrittr&)
) %dopar% Getjobs(i)
stopCluster(cl)
&/code&&/pre&&/div&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-076e59b6ab38da5bf6bc437f931cacfe_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&735& data-rawheight=&321& class=&origin_image zh-lightbox-thumb& width=&735& data-original=&https://pic4.zhimg.com/v2-076e59b6ab38da5bf6bc437f931cacfe_r.jpg&&&/figure&&p&&br&&/p&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-0c73ec50b18e24b931f905_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1125& data-rawheight=&758& class=&origin_image zh-lightbox-thumb& width=&1125& data-original=&https://pic1.zhimg.com/v2-0c73ec50b18e24b931f905_r.jpg&&&/figure&&p&&br&&/p&&p&总耗时5.14秒。&/p&&p&这里解释一下昨天的多进程下载pdf文件为何没有任何效果,我觉得是因为,对于网络I/O密集型的任务,网络下载过程带宽不足,耗时太久,几乎掩盖了多进程的时间节省(pdf文件平均5m)。&/p&&p&&b&Python版:&/b&&/p&&p&Python的案例使用urllib、lxml包进行演示。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&from urllib.request import urlopen,Request
import pandas as pd
import numpy as np
import time
from lxml import etree
&/code&&/pre&&/div&&p&方案1——使用显式循环抓取:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&def getjobs(i):
myresult = {
&job_item&:[],
&job_links&:[],
&job_info&:[],
&job_salary&:[],
&job_origin&:[]
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36',
'Referer':'https://www.hellobi.com/jobs/search'
while i & 11:
url = &https://www.hellobi.com/jobs/search?page={}&.format(i)
pagecontent=urlopen(Request(url,headers=header)).read().decode('utf-8')
result = etree.HTML(pagecontent)
myresult[&job_item&].extend(result.xpath('//div[@class=&job_item_middle pull-left&]/h4/a/text()'))
myresult[&job_links&].extend(result.xpath('//div[@class=&job_item_middle pull-left&]/h4/a/@href'))
myresult[&job_info&].extend([ text.xpath('string(.)').strip() for text in
result.xpath('//div[@class=&job_item_middle pull-left&]/h5')])
myresult[&job_salary&].extend(result.xpath('//div[@class=&job_item-right pull-right&]/h4/span/text()'))
myresult[&job_origin&].extend(result.xpath('//div[@class=&job_item-right pull-right&]/h5/span/text()'))
time.sleep(1)
print(&正在抓取第【{}】页&.format(i))
print(&everything is OK&)
return pd.DataFrame(myresult)
if __name__ == &__main__&:
t0 = time.time()
mydata1 = getjobs(list(range(1,11)))
t1 = time.time()
total = t1 - t0
print(&消耗时间:{}&.format(total))
&/code&&/pre&&/div&&p&&br&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-2e4dedb87bbc9a7b538da21b_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&964& data-rawheight=&519& class=&origin_image zh-lightbox-thumb& width=&964& data-original=&https://pic4.zhimg.com/v2-2e4dedb87bbc9a7b538da21b_r.jpg&&&/figure&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-89f7dfc33bd9c649a84139ffc1a59430_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1280& data-rawheight=&748& class=&origin_image zh-lightbox-thumb& width=&1280& data-original=&https://pic4.zhimg.com/v2-89f7dfc33bd9c649a84139ffc1a59430_r.jpg&&&/figure&&p&&br&&/p&&p&总耗时将近19秒,(代码中设置有时延,估测净时间在9秒左右)&/p&&p&&b&方案2——使用多线程方式抓取:&/b&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&def executeThread(i):
myresult = {
&job_item&:[],
&job_links&:[],
&job_info&:[],
&job_salary&:[],
&job_origin&:[]
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36',
'Referer':'https://www.hellobi.com/jobs/search'
url = &https://www.hellobi.com/jobs/search?page={}&.format(i)
pagecontent=urlopen(Request(url,headers=header)).read().decode('utf-8')
result = etree.HTML(pagecontent)
myresult[&job_item&].extend(result.xpath('//div[@class=&job_item_middle pull-left&]/h4/a/text()'))
myresult[&job_links&].extend(result.xpath('//div[@class=&job_item_middle pull-left&]/h4/a/@href'))
myresult[&job_info&].extend([ text.xpath('string(.)').strip() for text in
result.xpath('//div[@class=&job_item_middle pull-left&]/h5')])
myresult[&job_salary&].extend(result.xpath('//div[@class=&job_item-right pull-right&]/h4/span/text()'))
myresult[&job_origin&].extend(result.xpath('//div[@class=&job_item-right pull-right&]/h5/span/text()'))
with open('D:/Python/File/hellolive.csv', 'a+') as f:
pd.DataFrame(myresult).to_csv(f, index = False,header= False if i & 1 else True)
def main():
threads = []
for i in range(1,11):
thread = threading.Thread(target=executeThread,args=(i,))
threads.append(thread)
thread.start()
for i in threads:
if __name__ == '__main__':
t0 = time.time()
t1 = time.time()
total = t1 - t0
print(&消耗时间:{}&.format(total))
&/code&&/pre&&/div&&p&&br&&/p&&p&&br&&/p&&figure&&img src=&https://pic2.zhimg.com/v2-67b19a6e2c3ce6f20df4db_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&1280& data-rawheight=&1309& class=&origin_image zh-lightbox-thumb& width=&1280& data-original=&https://pic2.zhimg.com/v2-67b19a6e2c3ce6f20df4db_r.jpg&&&/figure&&p&&br&&/p&&p&&br&&/p&&p&以上多进程模式仅使用了1.64m,多进程爬虫的优势与单进程相比效率非常明显。&/p&&p&&b&方案3——使用多进程方式抓取:&/b&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&from
multiprocessing
import Pool
from urllib.request import urlopen,Request
import pandas as pd
import time
from lxml import etree
def executeThread(i):
myresult = {
&job_item&:[],
&job_links&:[],
&job_info&:[],
&job_salary&:[],
&job_origin&:[]
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36',
'Referer':'https://www.hellobi.com/jobs/search'
url = &https://www.hellobi.com/jobs/search?page={}&.format(i)
pagecontent=urlopen(Request(url,headers=header)).read().decode('utf-8')
result = etree.HTML(pagecontent)
myresult[&job_item&].extend(result.xpath('//div[@class=&job_item_middle pull-left&]/h4/a/text()'))
myresult[&job_links&].extend(result.xpath('//div[@class=&job_item_middle pull-left&]/h4/a/@href'))
myresult[&job_info&].extend([ text.xpath('string(.)').strip() for text in
result.xpath('//div[@class=&job_item_middle pull-left&]/h5')])
myresult[&job_salary&].extend(result.xpath('//div[@class=&job_item-right pull-right&]/h4/span/text()'))
myresult[&job_origin&].extend(result.xpath('//div[@class=&job_item-right pull-right&]/h5/span/text()'))
with open('D:/Python/File/hellolive.csv', 'a+') as f:
pd.DataFrame(myresult).to_csv(f, index = False,header= False if i & 1 else True)
def shell():
# Multi-process
pool = Pool(multiprocessing.cpu_count())
pool.map(excuteThread,list(range(1,11)))
pool.close()
pool.join()
if __name__ == &__main__&:
#计时开始:
t0 = time.time()
t1 = time.time()
total = t1 - t0
print(&消耗时间:{}&.format(total))
&/code&&/pre&&/div&&p&最后的多进程执行时间差不多也在1.5s左右,但是因为windows的forks问题,不能直接在编辑器中执行,需要将多进程的代码放在.py文件,然后将.py文件在cmd或者PowerShell中执行。&/p&&p&c从今天这些案例可以看出,对于网络I/O密集型任务而言,多线程和多进程确实可以提升任务效率,但是速度越快也意味着面临着更大的反爬压力,特别是在多进程/多线程环境下,并发处理需要做更加加完善的伪装措施,比如考虑提供随机UA/IP,以防过早被封杀。&/p&&p&&br&&/p&&p&在线课程请点击文末原文链接: &/p&&p&&a href=&https://link.zhihu.com/?target=https%3A//edu.hellobi.com/course/237& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Hellobi Live |日 R语言爬虫实战案例分享:网易云课堂、知乎live、今日头条、B站视频&/a&&/p&&p&往期案例数据请移步本人GitHub: &/p&&p&&a href=&https://link.zhihu.com/?target=https%3A//github.com/ljtyduyu/DataWarehouse/tree/master/File& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&github.com/ljtyduyu/Dat&/span&&span class=&invisible&&aWarehouse/tree/master/File&/span&&span class=&ellipsis&&&/span&&/a&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-1ee21cca7b9cf92daa22_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&548& data-rawheight=&314& class=&origin_image zh-lightbox-thumb& width=&548& data-original=&https://pic4.zhimg.com/v2-1ee21cca7b9cf92daa22_r.jpg&&&/figure&&p&&/p&
这一篇涉及到如何在网页请求环节使用多进程任务处理功能,因为网页请求涉及到两个重要问题:一是多进程的并发操作会面临更大的反爬风险,所以面临更严峻的反爬风险,二是抓取网页数据需要获取返回值,而且这些返回值需要汇集成一个关系表(数据框)(区别于…
&figure&&img src=&https://pic1.zhimg.com/v2-f5dd67a1d03d5ee39c86_b.jpg& data-rawwidth=&640& data-rawheight=&457& class=&origin_image zh-lightbox-thumb& width=&640& data-original=&https://pic1.zhimg.com/v2-f5dd67a1d03d5ee39c86_r.jpg&&&/figure&&p&作者:&b&晔无殊
&/b&R语言中文社区专栏作者&/p&&p&博客地址: &a href=&https://link.zhihu.com/?target=https%3A//github.com/eliseis/Statistical_Blog/blob/master/Missing_Value/MVI.md& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&github.com/eliseis/Stat&/span&&span class=&invisible&&istical_Blog/blob/master/Missing_Value/MVI.md&/span&&span class=&ellipsis&&&/span&&/a&&/p&&p&&br&&/p&&p&&b&1. 简介&/b&&/p&&p&1.1 缺失值的分类&/p&&p&
缺失值从数据分布上可被分为三类 (Gelman and Hill 2006, Little and Rubin (2002)) :missing completely at random (MCAR), missing at random (MAR), and missing not at random (MNAR)。&/p&&ul&&li&完全随机缺失(MCAR):某一变量缺失值不依赖于其他任何原因的完全随机缺失&/li&&li&随机缺失(MAR):某一变量的缺失与其他变量相关但与该变量本身的数值不相关&/li&&li&非随机缺失(NMAR):某一变量的缺失和该变量本身的数值相关, e.g., 仪器的最低检测线:某被检测物质的含量低于该检测线则会产生非随机缺失(left-censored missing)&/li&&/ul&&p&&br&&/p&&p&目前大部分填补缺失值的方法都是基于MCAR和MAR,这两种情况也相对比较难区别,因此本文会将这两种情况合并起来讨论。&/p&&p&&br&&/p&&p&&b&1.2 缺失值的可视化&/b&&/p&&p&
我一般拿到数据的第一件事就是用Amelia package (Honaker, King, and Blackwell 2011) 里面的missmap function看一下缺失值的分布情况。 &/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&require(magrittr)
require(Amelia)
load(file=&MVI.RData&)
missmap(test_na, col=c(&black&, &grey&), legend=FALSE, main = 'Missing Map')
&/code&&/pre&&/div&&figure&&img src=&https://pic2.zhimg.com/v2-3c20804eb5bbe475e7e9950eec263253_b.jpg& data-caption=&& data-size=&normal& data-rawwidth=&640& data-rawheight=&457& class=&origin_image zh-lightbox-thumb& width=&640& data-original=&https://pic2.zhimg.com/v2-3c20804eb5bbe475e7e9950eec263253_r.jpg&&&/figure&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 对于某一变量的缺失值识别可用is.na()sum(is.na(test_na$Var_1))
&/code&&/pre&&/div&&p&&br&&/p&&p&&b&1.3 为什么要对缺失值进行处理&/b&&/p&&p&&br&&/p&&p&对于MCAR,直接删除缺失的样本一般不会对结果产生偏差,但会减少样本数量;对于非完全随机确实特别是MNAR,如果缺失值较多则会对结果产生很大的偏移。另一方面,很多后续的统计检验要求完整的没有缺失值的数据集, e.g., principal components analysis (PCA).&/p&&p&&br&&/p&&p&2. 目前常用的缺失值处理方法&/p&&p&&b&2.1 行删除&/b&&/p&&p&2.1.1 直接删除有缺失值的样本&/p&&p&最简单粗暴的方法就是直接na.omit(),但是我们可以看到原来198个样本被删到了只剩4个。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&test_na_rm &- na.omit(test_na)
dim(test_na)
## [1] 198
dim(test_na_rm)
&/code&&/pre&&/div&&p&&b&2.1.2 80%法则&/b&&/p&&p&80%法则 (Bijlsma et al. 2006)认为,当某一物质的非缺失部分低于总样本量的80%时,建议删除该物质。Modified 80%法则认为, 当某一物质的非缺失部分低于所有生物学亚组的80%时,建议删除该物质。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# remove variables with missing & 20% mis_prop &- sapply(test_na, function(x) sum(is.na(x))/length(x))var_rm &- names(mis_prop)[mis_prop & 1 - 0.8]var_rm # remove 7 variables
## [1] &Var_1&
&Var_11& &Var_16& &Var_21&
test_na_rm &- test_na[, !colnames(test_na) %in% var_rm]test_na_rm &- na.omit(test_na_rm)
dim(test_na)
## [1] 198
dim(test_na_rm)
## [1] 83 23
&/code&&/pre&&/div&&p&去掉7个不符合80%法则的物质以后再用na.omit()删除有缺失的样本,最终的样本数量维持在了83个。&/p&&p&&b&2.2 单变量填补&/b&&/p&&p&用单一变量的均值/中位数/二分之一最小值/零值进行补值,这种方法会导致数据分布的偏移,方差偏小,PCA上会看到一条补值导致的直线等问题。&/p&&p&&br&&/p&&p&2.2.1 MCAR/MAR&/p&&p&对于MCAR/MAR,可以用均值/中位数补值。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# meantest_na_mean_imp &- lapply(test_na, function(x) {
x[is.na(x)] &- mean(x, na.rm = T)
})test_na_mean_imp_df &- do.call(cbind.data.frame, test_na_mean_imp)
# mediantest_na_median_imp &- lapply(test_na, function(x) {
x[is.na(x)] &- median(x, na.rm = T)
})test_na_median_imp_df &- do.call(cbind.data.frame, test_na_median_imp)
&/code&&/pre&&/div&&p&&b&2.2.2 MNAR&/b&&/p&&p&对于left-censored MNAR可以用二分之一最小值/零值进行补值。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# half of minimumtest_na_hm_imp &- lapply(test_na, function(x) {
x[is.na(x)] &- min(x, na.rm = T)/2
})test_na_hm_imp_df &- do.call(cbind.data.frame, test_na_hm_imp)
# zerotest_na_zero_imp_df &- test_natest_na_zero_imp_df[is.na(test_na_zero_imp_df)] &- 0
&/code&&/pre&&/div&&p&&b&2.3 多变量填补&/b&&/p&&p&多变量填补的前提是其他变量对于该变量的可预测性,用其他变量作为independent variable,含有缺失值的该变量作为dependent variable,建立模型,用模型来预测该变量中的缺失值。&/p&&p&2.3.1 MCAR/MAR&/p&&p&目前常用的补值方法大部分都是针对MCAR/MAR的情况:missForest (Stekhoven and Bühlmann 2012), k-nearest neighbors (kNN) (Troyanskaya et al. 2001), singular value decomposition (SVD) (T. Hastie, Tibshirani, and Sherlock 1999, Stacklies et al. (2007)), 等等。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 请先安装missForest packagerequire(missForest)# missForesttest_na_missForest_imp_df &- missForest(test_na)[[1]]
missForest iteration 1 in progress...done!
missForest iteration 2 in progress...done!
missForest iteration 3 in progress...done!
missForest iteration 4 in progress...done!
missForest iteration 5 in progress...done!
# 请先安装impute packagerequire(impute)# kNNtest_na_kNN_imp_df &-
test_na %&% data.matrix() %&% impute.knn() %&% extract2(1) %&% data.frame()
# 请先安装imputeLCMD packagerequire(imputeLCMD)# SVDSVD_wrapper &- function(data, K = 5) {
data_sc_res &- scale_recover(data, method = 'scale')
data_sc &- data_sc_res[[1]]
data_sc_param &- data_sc_res[[2]]
result &- data_sc %&% impute.wrapper.SVD(., K = K) %&%
scale_recover(., method = 'recover', param_df = data_sc_param) %&% extract2(1)
return(result)
}test_na_SVD_imp_df &- SVD_wrapper(test_na) %&% data.frame()
&/code&&/pre&&/div&&p&&br&&/p&&p&&b&2.3.2 MNAR&/b&&/p&&p&目前对于MNAR的算法开发非常有限,如quantile regression imputation of left-censored data (QRILC) (Lazar et al. 2016), gibbs sampler based left-censored missing value imputation approach (GSimp) (Wei et al. 2017).&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 请先安装imputeLCMD packagerequire(imputeLCMD)# QRILCQRILC_wrapper &- function(data, ...) {
zero_idx &- which(data == 0, arr.ind = T)
data_temp &- data
data_temp[zero_idx] &- NA
result &- data_temp %&% log() %&% impute.QRILC(., ...) %&% extract2(1) %&% exp()
result[zero_idx] &- 0
return(result)
}test_na_QRILC_imp_df &- QRILC_wrapper(test_na)
# GSimpsource('GSimp.R')sim_GS_wrapper &- function(data) {
result &- data %&% multi_impute(., iters_each=50, iters_all=10, initial='qrilc',
lo=-Inf, hi='min', n_cores=1, imp_model='glmnet_pred')
return(result$data_imp)
}test_na_GSimp_imp_df &- sim_GS_wrapper(test_na)
## Iteration 1 start...end!
## Iteration 2 start...end!
## Iteration 3 start...end!
## Iteration 4 start...end!
## Iteration 5 start...end!
## Iteration 6 start...end!
## Iteration 7 start...end!
## Iteration 8 start...end!
## Iteration 9 start...end!
## Iteration 10 start...end!
&/code&&/pre&&/div&&p&Core functions for GSimp are available at: GitHub(地址:&a href=&https://link.zhihu.com/?target=https%3A//github.com/WandeRum/GSimp& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&github.com/WandeRum/GSi&/span&&span class=&invisible&&mp&/span&&span class=&ellipsis&&&/span&&/a&)&/p&&p&&br&&/p&&p&&b&3. 不同补值方法的结果比较&/b&&/p&&p&请参考以下两篇文章: Missing Value Imputation Approach for Mass Spectrometry-based Metabolomics Data (Wei et al. 2017), GSimp: A Gibbs sampler based left-censored missing value imputation approach for metabolomics studies (Wei et al. 2017)。结果显示:在代谢组学的数据中,对于MCAR/MAR的缺失,推荐使用missForest进行补值; 对于left-censored MNAR的缺失,推荐使用GSimp进行补值。 注:以上方法还需在其他类型的数据中进行系统性的比较。&/p&&p&&br&&/p&&p&&b&4. 缺失值补值可视化软件 – MetImp&/b&&/p&&p&我们将以上各种补值方法 (GSimp很快也会添加进去) 做成了一个免费的web-tool: MetImp(地址:&a href=&https://link.zhihu.com/?target=https%3A//metabolomics.cc.hawaii.edu/software/MetImp/& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&metabolomics.cc.hawaii.edu&/span&&span class=&invisible&&/software/MetImp/&/span&&span class=&ellipsis&&&/span&&/a&)&/p&&ul&&li&Step 1: 上传数据,数据格式请保持和我们网站上example data一致; 即横行为样本,纵列为物质,第一行为物质名称,第一列为样本名称,第二列为组别信息;&/li&&li&Step 2: 选择缺失值是属于MCAR/MAR, 还是MNAR;&/li&&li&Step 3: 选择物质删除标准,非缺失部分低于总样本量的百分之多少时删除该物质;&/li&&li&Step 4: Run;&/li&&li&Step 5: 下载补值后的完整数据。&/li&&/ul&&p&请cite我们的文章:&/p&&ul&&li&Runmin Wei, Jingye Wang, Mingming Su, Erik Jia, Tianlu Chen, and Yan Ni.&/li&&li&&Missing Value Imputation Approach for Mass Spectrometry-based Metabolomics Data.& Scientific Reports (under revision).&/li&&li&Runmin Wei, Jingye Wang, Erik Jia, Tianlu Chen, Yan Ni, and Wei Jia.&/li&&li&“GSimp: A Gibbs sampler based left-censored missing value imputation approach for metabolomics studies.” PLOS Computational Biology (under revision).&/li&&/ul&&p&&b&5. 参考文献&/b&&/p&&p&Bijlsma, Sabina, Ivana Bobeldijk, Elwin R. Verheij, Raymond Ramaker, Sunil Kochhar, Ian A. Macdonald, Ben Van Ommen, and Age K. Smilde. 2006. “Large-scale human metabolomics studies: A strategy for data (pre-) processing and validation.” Analytical Chemistry 78 (2):567–74. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.1021/ac051495j& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.1021/ac05149&/span&&span class=&invisible&&5j&/span&&span class=&ellipsis&&&/span&&/a&.&/p&&p&Gelman, Andrew, and Jennifer Hill. 2006. Data analysis using regression and multilevel/hierarchical models.&a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.061& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.&/span&&span class=&invisible&&061&/span&&span class=&ellipsis&&&/span&&/a&.&/p&&p&Hastie, Trevor, Robert Tibshirani, and Gavin Sherlock. 1999. “Imputing missing data for gene expression arrays.” Technical Report, Division of Biostatistics, Stanford University, 1–9.&/p&&p&Honaker, James, Gary King, and Matthew Blackwell. 2011. “AMELIA II : A Program for Missing Data.” Journal of Statistical Software 45 (7):1–54. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.1.1.149.9611& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.1.1.149.9611&/span&&span class=&invisible&&&/span&&/a&.&/p&&p&Lazar, Cosmin, Laurent Gatto, Myriam Ferro, Christophe Bruley, and Thomas Burger. 2016. “Accounting for the Multiple Natures of Missing Values in Label-Free Quantitative Proteomics Data Sets to Compare Imputation Strategies.” Journal of Proteome Research 15 (4):1116–25. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.1021/acs.jproteome.5b00981& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.1021/acs.jpr&/span&&span class=&invisible&&oteome.5b00981&/span&&span class=&ellipsis&&&/span&&/a&.&/p&&p&Little, Roderick J a, and Donald B Rubin. 2002. Statistical Analysis with Missing Data. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.&/span&&span class=&invisible&&&/span&&/a&.&/p&&p&Stacklies, Wolfram, Henning Redestig, Matthias Scholz, Dirk Walther, and Joachim Selbig. 2007. “pcaMethods - A bioconductor package providing PCA methods for incomplete data.” Bioinformatics 23 (9):1164–7.&a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.1093/bioinformatics/btm069& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.1093/bioinfo&/span&&span class=&invisible&&rmatics/btm069&/span&&span class=&ellipsis&&&/span&&/a&.&/p&&p&Stekhoven, Daniel J., and Peter Bühlmann. 2012. “Missforest-Non-parametric missing value imputation for mixed-type data.” Bioinformatics 28 (1):112–18. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.1093/bioinformatics/btr597& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.1093/bioinfo&/span&&span class=&invisible&&rmatics/btr597&/span&&span class=&ellipsis&&&/span&&/a&.&/p&&p&Troyanskaya, O, M Cantor, G Sherlock, P Brown, T Hastie, R Tibshirani, D Botstein, and R B Altman. 2001. “Missing value estimation methods for DNA microarrays.” Bioinformatics (Oxford, England) 17 (6):520–25.&a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.1093/bioinformatics/17.6.520& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.1093/bioinfo&/span&&span class=&invisible&&rmatics/17.6.520&/span&&span class=&ellipsis&&&/span&&/a&.&/p&&p&Runmin Wei, Jingye Wang, Erik Jia, Tianlu Chen, Yan Ni, and Wei Jia. 2017. “GSimp: A Gibbs sampler based left-censored missing value imputation approach for metabolomics studies.” bioRxiv. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.&/span&&span class=&invisible&&&/span&&/a&.&/p&&p&Runmin Wei, Jingye Wang, Mingming Su, Erik Jia, Tianlu Chen, and Yan Ni. 2017. &Missing Value Imputation Approach for Mass Spectrometry-based Metabolomics Data.& bioRxiv. &a href=&https://link.zhihu.com/?target=https%3A//doi.org/10.& class=& external& target=&_blank& rel=&nofollow noreferrer&&&span class=&invisible&&https://&/span&&span class=&visible&&doi.org/10.&/span&&span class=&invisible&&&/span&&/a&.&/p&
作者:晔无殊 R语言中文社区专栏作者博客地址:
1. 简介1.1 缺失值的分类 缺失值从数据分布上可被分为三类 (Gelman and Hill 2006, Little and Rubin (2002)) :missing completely at random (MCAR), missing at random (MAR), and m…
&figure&&img src=&https://pic4.zhimg.com/v2-c76f851c3eaf66f6e570d43_b.jpg& data-rawwidth=&896& data-rawheight=&504& class=&origin_image zh-lightbox-thumb& width=&896& data-original=&https://pic4.zhimg.com/v2-c76f851c3eaf66f6e570d43_r.jpg&&&/figure&虽然计量经济学和统计学关系密切,但是两者存在较大的差异性。应用计量经济学主要是研究经济变量之间的关系,并且努力证明其为因果关系。这也是为什么现在在经管类实证研究文献中基于自然实验(Natural Experiment)的经验研究非常流行的原因。&p&除了学科本身的差异以外,两个群体用的工具也存在较大的差异。应用计量经济学的人较多的是用Stata,统计学的人较多的是用R。&/p&&br&&br&&ul&&li&事实上的通用工具Stata&/li&&/ul&&br&&p&Stata的优势在于提供一站式的软件包,并且也可以以ado文件的形式进行扩展,自带的PDF用户手册(TeX)非常详细。作为商业软件Stata为数据分析结果提供&a href=&https://link.zhihu.com/?target=http%3A//www.stata.com/why-use-stata/verifiably-accurate/index.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&verifiably accurate&/a&,&a href=&https://link.zhihu.com/?target=http%3A//www.stata.com/why-use-stata/pharmaceutical-health-industry/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&其分析结果被FDA认可。&/a&数据分析结果高度可信,这个优点得到每一个用户的喜欢。&/p&&p&当然了缺点也有,不然在应用计量领域中没有R的事情了。&/p&&p&如扩展丰富度不够(与R比);&/p&&p&一个窗口只能保留一个数据文件;&/p&&p&数据可视化水平一般&/p&&p&……&/p&&p&所以&a href=&https://link.zhihu.com/?target=https%3A//www.stata.com/meeting/chicago16/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&The 2016 Stata Conference&/a&开始考虑Stata与Web的交互能力,甚至考虑用Stata做出&a href=&https://link.zhihu.com/?target=https%3A//d3js.org/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&D3.js&/a&那样的数据可视化作品。&/p&&br&&br&&ul&&li&日益丰富的R&/li&&/ul&&br&&p&R语言的优点在网上有很多。这里就不多多说了。如可以操作多个数据集和对象、Rstudio提供良好的开发环境、丰富的画图包,静态的ggpot2,交互式的plotly、号称操作100GB数据的data.table、可以生成动态报告的rmarkdown、量化投资利器quantmod……在大数据的热潮中,微软加盟R语言社区,还专门发行了增强版的R语言MRO,并且在自己的产品中嵌入R。&/p&R语言这么厉害,当然也会被引入到应用计量经济学中。Kleiber and Zeileis(2008)写了一份小册子Applied Econometrics with R,这个算是比较早专门介绍R语言在应用计量经济学中的使用。因为这本书还有一个专门的R包AER。不过这个AER非彼AER(American Economic Review)。&p&Zeileis and Koenker(2008)在JSS上写了一篇文章,名字非常带感Econometrics in R: Past, Present, and Future。这么多年过去了,当年的Future已经是Present,只是现在这个Present估计还没有达到他们当年的预期。&/p&&p&R语言社区在CRAN Task View设立一个&a href=&https://link.zhihu.com/?target=https%3A//cran.r-project.org/web/views/Econometrics.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Econometrics&/a&,包的种类挺丰富:Basic linear regression、Microeconometrics、Instrumental variables、Panel data models、Further regression models、Time series data and models、Data sets和Miscellaneous。&/p&&p&面对眼花缭乱的包、风格迥异的操作,没有老司机带路,新手不敢上路呀。所以一般的新手纷纷奔向Stata阵营去了。因为围绕着Stata讲应用计量经济学的教程实在是太多了。&/p&&br&&br&&ul&&li&经管类小伙伴如何上手R&/li&&/ul&&p&Muenchen R A, Hilbe J. R for Stata users[M]. New York, New York: Springer, 2010.&br&&/p&&p&一本介绍转向R的书。&/p&&a href=&https://link.zhihu.com/?target=http%3A//www.princeton.edu/%7Emattg/statar/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&R FOR STATA USERS&/a&&br&&a href=&https://link.zhihu.com/?target=https%3A//github.com/EconometricsBySimulation/RStata/wiki/Dictionary%3A-Stata-to-R& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Dictionary: Stata to R&/a&&br&&a href=&https://link.zhihu.com/?target=http%3A//www.princeton.edu/%7Eotorres/RStata.pdf& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Getting Started in R~Stata&/a&&br&&p&这个三个材料很棒,简明,迅速!采用对比的手法,帮助Stata用户快速上手R。&/p&&p&Kleiber C, Zeileis A. Applied econometrics with R[M]. Springer Science & Business Media, 2008.&br&&/p&&p&比较全面的把R带入应用计量经济学。&/p&&p&Farnsworth G V. Econometrics in R[M]. 2014.&br&&/p&&p&70页的小册子,快速熟悉各类应用计量模型。&/p&&p&经管类的小伙伴一定对Wooldridge不陌生。如果把Wooldridge的Introductory Econometrics用R实现一遍是什么样的感觉?&/p&&p&哈哈,已经有牛人做了。这就是Heiss写的&a href=&https://link.zhihu.com/?target=http%3A//www.urfie.net/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Using R for Introductory Econometrics&/a&。&/p&&blockquote&&A very nice resource for those wanting to use R in their introductory econometrics courses.& (Jeffrey M. Wooldridge)&/blockquote&&p&这本书配套2016年版的Introductory Econometrics,而且还介绍了R with R Markdown or LaTeX。&a href=&https://zhuanlan.zhihu.com/p/& class=&internal&&想了解Rmarkdown点这里。&/a&&/p&&p&这本书提供了网页版,可以在线阅读。当然也可以在网上买实体书。&/p&&p&做资本市场数据的小伙伴手头上常常玩的是面板数据。R如何处理面板数据?&/p&&p&Croissant Y, Millo G. Panel data econometrics in R: The plm package[J]. Journal of Statistical Software, ): 1-43.&br&&/p&&p&上面这篇PDF是做面板的一个很好的读物。它对plm包做了十分细致的描述,应用的便捷程度不下于Stata的xtreg命令集。&/p&&p&Croissant and Millo(2016)干脆把2008年在JSS上的文章丰富一下,就整成了一本小册子。&br&&/p&&p&Croissant Y, Millo G. Panel Data Econometrics with R[M]. Wiley-Blackwell, 2016.&/p&&p&做时间序列(金融数据)的小伙伴可以阅读下面这本书。&/p&&p&Tsay R S. An introduction to analysis of financial data with R[M].&/p&&br&&br&&ul&&li&三个建议&/li&&/ul&&br&R发行版可以采用微软的版本&a href=&https://link.zhihu.com/?target=https%3A//mran.revolutionanalytics.com/download/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Microsoft R Open&/a&,充分利用多核处理器的优势。&p&IDE,IDE,IDE。尽量采用IDE,提高效率。可以用&a href=&https://link.zhihu.com/?target=https%3A//www.rstudio.com/products/rstudio/download/preview-release-notes/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Rstudio(preview-release)&/a&。&/p&&p&优先使用知名的包、一直在更新的包。这个很重要。&a href=&https://link.zhihu.com/?target=https%3A//r-how.com/packages& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&一个R包排行榜。&/a&&/p&&br&&br&&ul&&li&结束&/li&&/ul&&br&&p&到这里基本上已经介绍了R在应用计量经济学中的主要板块中的教程,可以放心学习上手R了。&/p&&p&不过……&/p&&p&R的包多是多,但是质量良莠不齐,代码风格不统一。&/p&&p&有些R包的说明文档解释不全,导致用户对各个参数的使用并不明晰。&/p&&p&The R Core Team特别提醒用户,“R is free software and comes with ABSOLUTELY NO WARRANTY ”。&/p&&p&前方有坑,小心驾驶……&/p&&p&======================================================================&/p&&p&更新1:&/p&&p&&a href=&https://link.zhihu.com/?target=https%3A//bookdown.org/ccolonescu/RPoE4/RPoE.pdf& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Principles of Econometrics with R&/a&,点击链接可以下载。这本书不错,2016出来的,比较全面展现了R在应用计量中的使用。&a href=&https://link.zhihu.com/?target=https%3A//github.com/ccolonescu/PoEdata& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&数据链接&/a&。&br&&/p&&p&更新2:&/p&&p&&a href=&https://link.zhihu.com/?target=http%3A//www.econ.uiuc.edu/%7Eecon472/e-Tutorial.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Applied Econometrics&/a&,采用R语言和Stata双语教学 &br&&/p&&p&有新材料出现,再补上&/p&
虽然计量经济学和统计学关系密切,但是两者存在较大的差异性。应用计量经济学主要是研究经济变量之间的关系,并且努力证明其为因果关系。这也是为什么现在在经管类实证研究文献中基于自然实验(Natural Experiment)的经验研究非常流行的原因。除了学科本身…
&figure&&img src=&https://pic2.zhimg.com/v2-215b8adfcfe783f6a7e9831_b.jpg& data-rawwidth=&1440& data-rawheight=&1080& class=&origin_image zh-lightbox-thumb& width=&1440& data-original=&https://pic2.zhimg.com/v2-215b8adfcfe783f6a7e9831_r.jpg&&&/figure&&h3&作者 Selva Prabhakaran&/h3&&h3&译者 钱亦欣&/h3&&h3&在处理一些真实数据时,样本中往往会包含缺失值(Missing values)。我们需要对缺失值进行适宜的处理,才能建立更为有效的模型,使得后续预测分析能有更小的偏差。本文将罗列不同的缺失值处理方法,并进行具体应用。&/h3&&h2&数据准备和缺失模式设定&/h2&&h3&本文使用mlbench包中的BostonHousing数据集作为示例来演示不同的缺失值处理方法。由于原始的数据集并不包含缺失值,我们需要随机删除一些数据。通过这种方法,我们不仅可以评估由数据缺失带来的精度损失,也可以比较不同处理方式的效果好坏。让我们先加载这个数据集,并随机删除一些数据。&/h3&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 加载数

我要回帖

更多关于 r语言 data.frame 的文章

 

随机推荐