参见:https://rafalab.github.io/dsbook/web-scraping.html

    可以通过rvest 库的read_html 方法来读取html 数据,可以通过url 链接或文件直接读取:

    1. > library(rvest)
    2. > tmp = read_html("~/Desktop/11.html")
    3. > tmp = read_html("http://www.sse.com.cn/market/sseindex/indexlist/s/i000001/const_list.shtml")
    4. > tmp
    5. {html_document}
    6. <html xmlns="http://www.w3.org/1999/xhtml">
    7. [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ...
    8. [2] <body>\r\n\t\t<table id="container" align="center" cellspacing="0" cellpa ...

    检查一下文件类型:

    1. > class(tmp)
    2. [1] "xml_document" "xml_node"

    可见直接对该对象操作,是一头雾水的,接着用html_text 函数,可以获得页面的全部html 信息,紧接着可以用html_nodes 函数提取”table” 内容:

    1. a <- html_text(tmp)
    2. class(a)
    3. > substr(a, 1, 100)
    4. [1] "上海证券交易所_上证综合指数成分股列表var col_id=\"359\" \r\n\t\t\r\n\tfunction bluring() {\r\n\t\tif (event.srcElement.tagName == '"
    5. > b <- html_nodes(tmp, "table")
    6. > b
    7. {xml_nodeset (5)}
    8. [1] <table id="container" align="center" cellspacing="0" cellpa ...
    9. [2] <table height="100%" class="wrap">\n<tr height="210" class= ...
    10. [3] <table id="Area"><tr>\n<td id="A_Area" width="192" valign=" ...
    11. [4] <table border="0" cellspacing="0" cellpadding="0"><tr>\n<td ...
    12. [5] <table class="tablestyle">\n<tr bgcolor="white">\n<td class ...

    接着再用html_table 函数,我们就可以直接获得tibble 数据框了,感觉这样通过node 直接查找table,比xpath 查找方便了不少,而先前静态网站数据尝试中获得的表格也就是在:

    d <- html_table(b)
    > d[[5]]
    # A tibble: 522 x 3
       X1                    X2                   X3                  
       <chr>                 <chr>                <chr>               
     1 "浦发银行\r\n       ~ "白云机场\r\n      ~ "东风汽车\r\n      ~
     2 "中国国贸\r\n       ~ "首创股份\r\n      ~ "上海机场\r\n      ~
     3 "包钢股份\r\n       ~ "华能国际\r\n      ~ "皖通高速\r\n      ~
     4 "华夏银行\r\n       ~ "民生银行\r\n      ~ "日照港<U+00A0><U+00A0>\r\n      ~
     5 "上港集团\r\n       ~ "宝钢股份\r\n      ~ "中原高速\r\n      ~
     6 "上海电力\r\n       ~ "山东钢铁\r\n      ~ "浙能电力\r\n      ~
     7 "华能水电\r\n       ~ "中远海能\r\n      ~ "华电国际\r\n      ~
     8 "中国石化\r\n       ~ "南方航空\r\n      ~ "中信证券\r\n      ~
     9 "三一重工\r\n       ~ "福建高速\r\n      ~ "楚天高速\r\n      ~
    10 "招商银行\r\n       ~ "歌华有线\r\n      ~ "中直股份\r\n      ~
    # ... with 512 more rows
    

    其他要做的,实际上也就是把数据清理一下的简单工作。