爬虫是都不陌生的一个概念,比如百度、谷歌都有自己的爬虫工具去抓取网站、分析、索引,方便我们的查询使用。 在我们浏览网站、查询信息时,如果想做一些批量的处理,也可以去分析网站的结构、抓取网页、提取信息,然后就完成了一个小爬虫的写作。 网页爬虫需要我们了解 HMDB (人类代谢组数据库)收录了很多代谢组的数据,用于代谢组学、临床化学、生物标志物开啊和基本教育等。数据联通化学、临床、分子生物学3个层次,共有114,099个代谢物。 网站提供了多种浏览和查询功能,可以关注不同的疾病、通路、BMI、年龄、性别相关代谢组学。 下图展示的是BMI相关代谢物的数据。 如果我们想把这个表格下载下来,一个办法是一页页的拷贝,大约拷贝十几次,工作量不算太大,但有些无趣。另外一个办法就是这次要说的抓取网页。 R的 # Load the package required to read website > str(df1)List of 1 $ NULL:'data.frame': 25 obs. of 7 variables: ..$ V1: chr [1:25] 'Butyrylcarnitine (HMDB0002013)' 'Alpha-ketoisovaleric acid (HMDB0000019)' '2-Hydroxy-3-methylbutyric acid (HMDB0000407)' '3-Methyl-2-oxovaleric acid (HMDB0000491)' ... ..$ V2: chr [1:25] '' '' '' '' ... ..$ V3: chr [1:25] 'Increase' 'Increase' 'Increase' 'Increase' ... ..$ V4: chr [1:25] 'Blood' 'Blood' 'Blood' 'Blood' ... ..$ V5: chr [1:25] '9.95e-10' '2.87e-08' '1.19e-05' '1.68e-05' ... ..$ V6: chr [1:25] '25254000' '25254000' '25254000' '25254000' ... ..$ V7: chr [1:25] 'details' 'details' 'details' 'details' ... # The readHTMLTable returns list, we need to extract our data frame. In this example, the first element is our data frame, so we can extract it like this: 1 Butyrylcarnitine (HMDB0002013) Increase Blood 9.95e-102 Alpha-ketoisovaleric acid (HMDB0000019) Increase Blood 2.87e-083 2-Hydroxy-3-methylbutyric acid (HMDB0000407) Increase Blood 1.19e-054 3-Methyl-2-oxovaleric acid (HMDB0000491) Increase Blood 1.68e-055 Ketoleucine (HMDB0000695) Increase Blood 6.05e-056 (S)-3-Hydroxyisobutyric acid (HMDB0000023) Increase Blood 6.88e-05 V6 V71 25254000 details2 25254000 details3 25254000 details4 25254000 details5 25254000 details6 25254000 details 这样我们就获得了第一页的表格,如果想获得随后的页的呢?鼠标移动经过分页的标签,可以看到URL的规律。
# 294是在网页直接看到的总条数,25是每页显示的条数。(也是可以自动解析判断的) 这样就获得了所有的表格。 有两点需要注意
问题解决可能是因为网速或其它问题,有时直接把 # Load the package required to read websitelibrary(XML)# wegpage address url <- 'http://www./bmi_metabolomics'#="" method="" one:="" for="" people="" who="" is="" luckiest="" (not="" me,="" so="" sad)df1="">-><- readhtmltable(url,="" header="T," stringsasfactors="F)" #="" error:="" failed="" to="" load="" external="" entity="" 'url'#="" method="" two:="" use="" rcurl="" package,="" for="" people="" who="" is="" much="" luckier="" (only="" work="" on="" my="" laptop,="" not="" the="" computer="" in="" the="" office,="" crying)library(rcurl)xmldoc="">-><- geturl(url)df2="">-><- readhtmltable(xmldoc,="" stringsasfactors="F)#" method="" three:="" use="" httr="" package,="" for="" people="" who="" is="" not="" luckylibrary(httr)tabs="">-><- get(url)df3="">-><- readhtmltable(rawtochar(tabs$content),="" as.data.frame="T," stringsasfactors="">-> 便捷链接
精品回顾
|
|