使用 rvest 和 css 选择器从抓取的搜索结果中提取 table
use rvest and css selector to extract table from scraped search results
刚刚在 Hadley 的 webinar 上了解到 rvest
并第一次尝试。
我想从 Google 搜索结果中抓取(然后绘制)棒球排名 table return。
我的问题是我无法进入 rvest
我在浏览器插件中看到的 table。
library(rvest)
library(magrittr) # for %>% operator
( g_search <-html_session(url = "http://www.google.com/?q=mlb+standings",
add_headers("user-agent" = "Mozilla/5.0")) )
# <session> http://www.google.com/?q=mlb+standings
# Status: 200
# Type: text/html; charset=UTF-8
# Size: 52500
此搜索应该 return 一个 table 隐藏在许多层之下但由 <div class="tb_strip">
唯一标识的页面。在 CSS Diner 快速停下来告诉我(我认为)"div.tb_strip" 是一个有效的 CSS 选择器来捕获这个 table(可能还有其他垃圾)。事实上,使用 Firebug 的 CSS 选择器,我看到了完整路径:
# Use Firebug "Copy CSS Path" and paste into table_path
table_path <- "html body#gsr.srp.tbo.vasq div#main div#cnt.big div.mw div#rcnt div.col div#center_col div#res.med div#search div div#ires ol#rso li.g.tpo.knavi.obcontainer div.kp-blk div#uid_0.r-iCGI_bFBahQE.xpdbox.xpdopen div div.lr_container.mod div#lr_tab_unit_uid_1.tb_u.r-igQv_rxlT08k div.tb_view div.tb_strip"
但是,由于 html_nodes
return 是一个空列表,以下访问此 table 的尝试失败。
( standings <- g_search %>%
html_nodes("div.tb_strip") %>%
html_table()
) #returns empty list
内容似乎没有进入 g_search,所以我还不知道 CSS 选择器是否有效。
grep("tb_strip",html_text(read_html("http://www.google.com/?q=mlb+standings")) ) # empty
它去哪儿了?
TYVM
这是一个来自更简单网站的示例...
library("rvest")
url <- "http://sports.yahoo.com/mlb/standings/"
html(url) %>% html_nodes(".yui3-tabview-content") %>% html_nodes("table") %>%html_table
刚刚在 Hadley 的 webinar 上了解到 rvest
并第一次尝试。
我想从 Google 搜索结果中抓取(然后绘制)棒球排名 table return。
我的问题是我无法进入 rvest
我在浏览器插件中看到的 table。
library(rvest)
library(magrittr) # for %>% operator
( g_search <-html_session(url = "http://www.google.com/?q=mlb+standings",
add_headers("user-agent" = "Mozilla/5.0")) )
# <session> http://www.google.com/?q=mlb+standings
# Status: 200
# Type: text/html; charset=UTF-8
# Size: 52500
此搜索应该 return 一个 table 隐藏在许多层之下但由 <div class="tb_strip">
唯一标识的页面。在 CSS Diner 快速停下来告诉我(我认为)"div.tb_strip" 是一个有效的 CSS 选择器来捕获这个 table(可能还有其他垃圾)。事实上,使用 Firebug 的 CSS 选择器,我看到了完整路径:
# Use Firebug "Copy CSS Path" and paste into table_path
table_path <- "html body#gsr.srp.tbo.vasq div#main div#cnt.big div.mw div#rcnt div.col div#center_col div#res.med div#search div div#ires ol#rso li.g.tpo.knavi.obcontainer div.kp-blk div#uid_0.r-iCGI_bFBahQE.xpdbox.xpdopen div div.lr_container.mod div#lr_tab_unit_uid_1.tb_u.r-igQv_rxlT08k div.tb_view div.tb_strip"
但是,由于 html_nodes
return 是一个空列表,以下访问此 table 的尝试失败。
( standings <- g_search %>%
html_nodes("div.tb_strip") %>%
html_table()
) #returns empty list
内容似乎没有进入 g_search,所以我还不知道 CSS 选择器是否有效。
grep("tb_strip",html_text(read_html("http://www.google.com/?q=mlb+standings")) ) # empty
它去哪儿了?
TYVM
这是一个来自更简单网站的示例...
library("rvest")
url <- "http://sports.yahoo.com/mlb/standings/"
html(url) %>% html_nodes(".yui3-tabview-content") %>% html_nodes("table") %>%html_table