【问题标题】:Webscraping in R, accessing html nodesR中的Web抓取,访问html节点
【发布时间】:2015-11-13 17:58:48
【问题描述】:

rvest 包的简单应用:我正在尝试从站点中抓取一类 html 链接。

这段代码为我提供了站点中正确的节点:

library(rvest)
library(magrittr)

foo <- "http://www.realclearpolitics.com/epolls/2010/house/2010_elections_house_map.html" %>% 
            read_html

另外,我使用 css 选择器找到了正确的节点:

foo %>% 
  html_nodes("#states td") %>% 
  extract(2:4)

返回

{xml_nodeset (3)}
[1] <td>\n  <a class="dem" href="/epolls/2010/house/ar/arkansas_4th_district_rankin_vs_ross-1343.html">\n    <span>AR4</span>\n  </a>\n</td>
[2] <td>\n  <a class="dem" href="/epolls/2010/house/ct/connecticut_1st_district_brickley_vs_larson-1713.html">\n    <span>CT1</span>\n  </a>\n</td>
[3] <td>\n  <a class="dem" href="/epolls/2010/house/ct/connecticut_2nd_district_peckinpaugh_vs_courtney-1715.html">\n    <span>CT2</span>\n  </a>\n</td>

好的,所以href 属性就是我要找的。但是这个

foo %>% 
  html_nodes("#states td") %>% 
  extract(2:4) %>% 
  html_attr("href")

返回

[1] NA NA NA

如何访问底层链接?

【问题讨论】:

  • 试试foo %&gt;% html_nodes("#states td a") %&gt;% extract(2:4) %&gt;% html_attr("href")
  • @jay 你应该回答这个问题。 tomw:你的目标不是主播,而 Jay 的解决方案是。

标签: r web-scraping rvest


【解决方案1】:

使用xml_children(),您可以:

foo %>% 
  html_nodes('#states td') %>% 
  xml_children %>%
  html_attr('href') %>%
  extract(2:4)

返回:

[1] "/epolls/2010/house/ar/arkansas_4th_district_rankin_vs_ross-1343.html"            
[2] "/epolls/2010/house/ct/connecticut_1st_district_brickley_vs_larson-1713.html"     
[3] "/epolls/2010/house/ct/connecticut_2nd_district_peckinpaugh_vs_courtney-1715.html"

您可以将extract 放在html_attr 前面,可能还有其他一些序列也可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多