网络上有大量的信息与数据。我们可以利用爬虫技术来获取这些巨大的数据资源。

这次用 IMDb 网站的2018年100部最欢迎的电影 来练练手,顺便总结一下 R 爬虫的方法。

##### >> Preparation


感谢 Hadley Wickham 大大,我们有 rvest 包可以用。因此爬虫前先安装并加载 rvest 包。

#install package
install.package('rvest')
#loading library
library('rvest')

##### >> Downloading and parsing HTML file


指定网页地址并且使用 read_html() 函数将网页转为 XML 对象。

url <- 'https://www.imdb.com/search/title?count=100&release_date=2018-01-01,2018-12-31&view=advanced'
webpage <- read_html(url)

##### >> Extracting Nodes


我期望获取的数据包括:

  1. Rank: 排名
  2. Title:电影名称
  3. Runtime:电影时长
  4. Genre:电影类型
  5. Rating:观众评分
  6. Metascore:媒体评分
  7. Description:电影简介
  8. Votes:观众投票支持的票数
  9. Gross:电影票房

使用 html_nodes() 函数可以提取 XML 对象中的元素。其中该函数利用 CSS 选择器来匹配吻合的元素。

#Using CSS selectors to extract node
rank_data_html <- html_nodes(webpage, '.text-primary')
#Converting the node to text
rank_data <- html_text(rank_data_html)
#Converting text value to numeric value
rank_data <- as.numeric(rank_data)

因为需要利用 CSS 选择器, 所以这个部分或许需要一点 HTML/CSS 的基础知识。如果不熟悉 HTML/CSS,分享一个小方法:

  1. 用浏览器(以 Chrome 为例)打开那个网页,然后按 F12 打开开发者工具
  2. 点击开发者工具左上角的箭头去选择那个需要爬取的数据
  3. 对应的那行代码就会在右侧的开发者工具被选中
  4. 对着 CSS 选择器的文档查查就知道该怎么写了

接着用类似的 Script 提取其他元素的数据。

##### >> Handling Missing Values


爬取元素后,如果仔细检查每组元素的长度,就会发现其实某些元素是有缺失值的。比如说 Metascore

metascore_data_html <- html_nodes(webpage,'.metascore')
metascore_data <- html_text(metascore_data_html)
length(metascore_data)

怎么将网页中不存在的相应值用 NA 表示呢?

这里要了解一下 html_nodehtml_nodes 的区别了。运行 ?html_node 查看帮助文档:

html_node is like [[ it always extracts exactly one element. When given a list of nodes, html_node will always return a list of the same length, the length of html_nodes might be longer or shorter.

所以简单地说,就是我们可以先提取一组没有缺失值的父级 DOM,然后从这组 DOM 中逐个提取所需的子级 DOM。

粗暴地说,上代码:

metascore_data_html <- html_node(html_nodes(webpage, '.lister-item-content'), '.metascore')
metascore_data <- html_text(metascore_data_html)
length(metascore_data)

##### >> Making a Data Frame


等所有数据都爬取完毕,就可以将其组合成 data frame 用于后续的分析了。

movies <- data.frame(
rank = rank_data,
title = title_data,
description = description_data,
runtime = runtime_data,
genre = genre_data,
rating = rating_data,
metascorre = metascore_data,
votes = votes_data,
gross = gross_data
)

##### >> Exporting CSV File


如果不想马上开始分析工作,还可以存为 csv 文件以后用。

write.csv(movies, file = file.choose(new = TRUE), row.names = FALSE)

搞定爬虫后,现在网络上已经有很多数据资源等我们用咯。

##### >> Notes


rvest 包还有其他有用的函数可以发掘一下的:

  1. html_tag(): 提取DOM 的 tag name
  2. html_attr(): 提取DOM 的 一个属性
  3. html_attrs(): 提取DOM 的 所有属性
  4. guess_encoding() and repair_encoding(): 检测编码和修复编码 (爬取中文网页的时候会用的到的~)
  5. jump_to(), follow_link(), back(), forward(): 爬取多页面网页的时候或许会用到

##### >> Sample Code


download here

Web Scraping with R: How to Fill Missing Value (爬虫:如何处理缺失值)的更多相关文章

  1. 阅读OReilly.Web.Scraping.with.Python.2015.6笔记---Crawl

    阅读OReilly.Web.Scraping.with.Python.2015.6笔记---Crawl 1.函数调用它自身,这样就形成了一个循环,一环套一环: from urllib.request ...

  2. 首部讲Python爬虫电子书 Web Scraping with Python

    首部python爬虫的电子书2015.6pdf<web scraping with python> http://pan.baidu.com/s/1jGL625g 可直接下载 waterm ...

  3. Web Scraping with Python读书笔记及思考

    Web Scraping with Python读书笔记 标签(空格分隔): web scraping ,python 做数据抓取一定一定要明确:抓取\解析数据不是目的,目的是对数据的利用 一般的数据 ...

  4. [Node.js] Web Scraping with Pagination and Advanced Selectors

    When web scraping, you'll often want to get more than just one page of data. Xray supports paginatio ...

  5. <Web Scraping with Python>:Chapter 1 & 2

    <Web Scraping with Python> Chapter 1 & 2: Your First Web Scraper & Advanced HTML Parsi ...

  6. Web scraping with Python (part II) « Jean, aka Sig(gg)

    Web scraping with Python (part II) « Jean, aka Sig(gg) Web scraping with Python (part II)

  7. 《Web Scraping With Python》Chapter 2的学习笔记

    You Don't Always Need a Hammer When Michelangelo was asked how he could sculpt a work of art as mast ...

  8. Web Scraping with Python

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  9. 阅读OReilly.Web.Scraping.with.Python.2015.6笔记---找出网页中所有的href

    阅读OReilly.Web.Scraping.with.Python.2015.6笔记---找出网页中所有的href 1.查找以<a>开头的所有文本,然后判断href是否在<a> ...

随机推荐

  1. Codeforces 660E Different Subsets For All Tuples【组合数学】

    看了官方题解+q神的讲解才懂... 智商问题.. 讲道理..数学真的比脱单难啊... 题目链接: http://codeforces.com/problemset/problem/660/E 题意: ...

  2. Spring中使用byType实现Beans自动装配

    以下内容引用自http://wiki.jikexueyuan.com/project/spring/beans-auto-wiring/spring-autowiring-byType.html: 此 ...

  3. dtrace

    http://blog.csdn.net/lw1a2/article/details/7389323

  4. Openwrt 安装软件到U盘或硬盘

    http://blog.licess.org/openwrt-install-software-to-udisk-harddisk/ 运行一个多月的DDNAS被结婚来玩的小孩给关了,于是趁机更新了一下 ...

  5. [RxJS] Create a Reusable Operator from Scratch in RxJS

    With knowledge of extending Subscriber and using source.lift to connect a source to a subscriber, yo ...

  6. [Analytics] Add Tealium debugger in Chrome

    It would be helpful once you can see what information have been tracking inside you web application, ...

  7. POJ3264Balanced Lineup(最基础的线段树)

    採用一维数组建树. (由于一维数组建的是全然二叉树,时间上比用孩子节点指针建树慢.只是基本能够忽略=-=) #include<iostream> #include<cstdio> ...

  8. easyUI 验证控件应用、自己定义、扩展验证 手机号码或电话话码格式

    easyUI 验证控件应用.自己定义.扩展验证 手机号码或电话话码格式 在API中   发现给的demo 中没有这个验证,所以就研究了下. 相关介绍省略,直接上代码吧! watermark/2/tex ...

  9. C语言最小生成树prim算法(USACO3.1)

    /* ID: hk945801 LANG: C++ TASK: agrinet */ #include<iostream> #include<cstdio> using nam ...

  10. APache POI emaple ()

    Business Plan The BusinessPlan application creates a sample business plan with three phases, weekly ...