【问题标题】:Scraping data from tables in a website using R使用 R 从网站中的表中抓取数据
【发布时间】:2016-01-17 14:15:00
【问题描述】:

我正在尝试在 R 中学习网络抓取,并且我正在尝试从以下链接 List of Cuisines on Wiki 中的各种表中抓取数据。在页面的底部有几个表格,列出了不同种类的美食,我想分别阅读它们。我尝试使用 css-selectors,但我认为我使用错了这是我的代码 sn-p:

require(rvest)
require(magrittr)
connection = html_session("https://en.wikipedia.org/wiki/List_of_cuisines")
connection %>% html_nodes("table:nth-child(1) a") %>% html_text()
#This lists down all the links in every table there is on that website
#I also tried connection %>% html_nodes("table:nth-child(2) a") %>% html_text()
#which gave a different list altogether

我试图生成的输出应该类似于

  1. 美食
    • 所有美食列表
  2. 非洲美食
    • 非洲美食一览

等等,这个列表是从 HTML 表格中填充的。

我非常感谢一些指导。谢谢。

【问题讨论】:

    标签: css r web-scraping


    【解决方案1】:

    这使用 XPath 并为您获取所有单独的链接。我这样做是为了展示如何使用 XPath 进行“松散”的子目标定位(您也可以使用 CSS 选择器进行学位)。希望它足以让你思考去做你想做的事情。基本上你可以把它分成两个步骤,一个是获取单个表,另一个是获取它们下面的链接:

    library(xml2)
    library(rvest)
    
    pg <- html_session("https://en.wikipedia.org/wiki/List_of_cuisines")
    
    links <- html_nodes(pg, xpath="//table[contains(@class, 'navbox')]//
                                      table[contains(@class, 'nowraplinks')]//
                                       td[contains(@class, 'navbox-list')]//
                                        li/a")
    
    length(links)
    ## [1] 1005
    
    head(html_attr(links, "href"), 20)
    ##  [1] "/wiki/African_cuisine"                 
    ##  [2] "/wiki/North_African_cuisine"           
    ##  [3] "/wiki/West_African_cuisine"            
    ##  [4] "/wiki/List_of_African_cuisines"        
    ##  [5] "/wiki/Cuisine_of_the_Americas"         
    ##  [6] "/wiki/North_American_cuisine"          
    ##  [7] "/wiki/South_American_cuisine"          
    ##  [8] "/wiki/List_of_cuisines_of_the_Americas"
    ##  [9] "/wiki/Asian_cuisine"                   
    ## [10] "/wiki/Central_Asian_cuisine"           
    ## [11] "/wiki/South_Asian_cuisine"             
    ## [12] "/wiki/List_of_Asian_cuisines"          
    ## [13] "/wiki/Balkan_cuisine"                  
    ## [14] "/wiki/Bengali_cuisine"                 
    ## [15] "/wiki/Caribbean_cuisine"               
    ## [16] "/wiki/Caucasian_cuisine"               
    ## [17] "/wiki/European_cuisine"                
    ## [18] "/wiki/Central_European_cuisine"        
    ## [19] "/wiki/Eastern_European_cuisine"        
    ## [20] "/wiki/List_of_European_cuisines"
    

    【讨论】:

    • 我正在寻找这样的东西,它确实有帮助。 @hrbrmstr XPath 显然是一种更好的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 2013-05-21
    相关资源
    最近更新 更多