从单个表格中抓取网页,文本是我想要的,但表格中的 href 链接来自整个页面.如何限制



我想使用 Rvest 包从 http://wfmu.org/playlists 的一个表中提取 href 链接。 当我用html_table()检查时,我可以抓住一个表格并确认我拥有的表格是正确的,但是当我在提取的表格上使用html_attr(name='href')时,我得到了整个页面上存在的链接。我不知道他们来自哪里。为什么当我确认我从页面上的一个表开始时,我得到了整个页面的链接? 谢谢。

#test web scrape
library(rvest)
library(tidyverse)
rawDJURLs<- read_html(paste('http://wfmu.org/playlists',sep=""))
# get the urls of the each DJ's playlist feed
#table 9 is off sched. tables 2-8 are monday through sunday
t_monday<-rawDJURLs%>%html_node(xpath='//html//body//center[2]//table[1]//table[2]')

确认我们得到的表格是周一早上的阵容

t_monday %>% html_table() %>% .[1,2]
[1] "The WoofMoo Morning Shown- playlists and archives...
t_off<-rawDJURLs%>%html_node(xpath='//html//body//center[2]//table[1]//table[9]')

确认我们得到的表是计划外的阵容

t_off %>% html_table() %>% .[1,2]
[1] "100% Whatevernwith Mary Wingn- playlists and archives...

但是当我提取 href 链接时,两者都包含相同的整个链接页面!

t_monday%>% html_nodes(xpath='//a[contains(.,"Playlists")]')  %>% 
  html_attr(name="href") -> l_monday
t_off%>% html_nodes(xpath='//a[contains(.,"Playlists")]')  %>% 
  html_attr(name="href") -> l_off
l_off==l_monday
 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE   
....    
[287] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
在我看来

,问题在于您用于收集表内链接的XPATH('//a[contains(.,"Playlists")]'(对于整个HTML页面是绝对的。我结合了两个 XPATH(用于表格和链接(并且它有效:

library(rvest)
library(tidyverse)
rawDJURLs<- read_html(paste('http://wfmu.org/playlists',sep=""))
l_off<-rawDJURLs %>%
  html_nodes(xpath='//html//body//center[2]//table[1]//table[9]//a[contains(.,"Playlists")]') %>% 
  html_attr(name="href")
l_monday<-rawDJURLs %>%
  html_nodes(xpath='//html//body//center[2]//table[1]//table[2]//a[contains(.,"Playlists")]') %>% 
  html_attr(name="href")
length(l_monday)
[1] 11
length(l_off)
[1] 236

最新更新