HTML 简介

R 语言网页抓取

Timo Grossenbacher

Instructor

看得见,就能抓取

不可下载

R 语言网页抓取

超文本标记语言(HTML)

<html> 
  <body> 
    <h2>A first example</h2>
    <p>A text paragraph.</p>
    <p>
      Here follows a list:
    </p>
  </body> 
</html>

HTML 介绍

R 语言网页抓取

HTML 具有层级结构

HTML 介绍

...
    <div>
      Here follows a list:
      <ul>
        <li>Bullet 1</li>
        <li>Bullet 2</li>
        <li>Bullet 3</li>
      </ul>
    </div>
...
R 语言网页抓取

HTML 标签可带属性

HTML 介绍

...
    <p>
      Here follows a 
      <a href="https://google.com">link</a>.
    </p>
...
R 语言网页抓取

用 R 读取 HTML

library(rvest)
html <- read_html(html_document)
html
{html_document}
<html>
[1] <body> \n    <h2>A first example</h2>\n    <p>A text paragraph.</p>\n   ...
class(html)
"xml_document" "xml_node"
R 语言网页抓取
library(xml2)
xml_structure(html)
<html>
  <body>
    {text}
    <h2>
      {text}
    {text}
    <p>
      {text}
    {text}
    <p>
      {text}
      <a [href]>
        {text}
      {text}
    {text}
R 语言网页抓取

让我们解析 HTML!

R 语言网页抓取

Preparing Video For Download...