2017-10-21 158 views
0

我试图用rvest从维基百科(包括从其他网页链接)拉ISO国家简介。我找不到包含名称的正确获取链接(href属性)的方法(我试过xpath字符串函数会导致错误)。运行起来相当容易 - 而且自我解释。的R - 网页刮痧 - 麻烦获取属性值使用rvest

任何帮助表示赞赏!

library(rvest) 
library(dplyr) 

searchPage <- read_html("https://en.wikipedia.org/wiki/ISO_3166-2") 
nodes <- html_node(searchPage, xpath = '(//h2[(span/@id = "Current_codes")]/following-sibling::table)[1]') 
codes <- html_nodes(nodes, xpath = 'tr/td[1]/a/text()') 
names <- html_nodes(nodes, xpath = 'tr/td[2]//a[@title]/text()') 
#Following brings back data but attribute name as well 
links <- html_nodes(nodes, xpath = 'tr/td[2]//a[@title]/@href') 
#Following returns nothing 
links2 <- html_nodes(nodes, xpath = 'tr/td[2]//a[@title]/@href/text()') 
#Following Errors 
links3 <- html_nodes(nodes, xpath = 'string(tr/td[2]//a[@title]/@href)') 
#Following Errors 
links4 <- sapply(nodes, function(x) { x %>% read_html() %>% html_nodes("tr/td[2]//a[@title]") %>% html_attr("href") }) 

回答

0

您应该在您的问题中包含更多信息。 “不言自明的”几乎让我忽略了这个问题(提示:考虑提供足够的口头细节以尊重他人的时间以及破碎的代码)。

我说,B/C我不知道如果这是你需要什么,或者没有B/C,你真是没的说。

library(rvest) 
library(tibble) 

pg <- read_html("https://en.wikipedia.org/wiki/ISO_3166-2") 

tab <- html_node(pg, xpath=".//table[contains(., 'Zimbabwe')]") 

iso_col <- html_nodes(tab, xpath=".//td[1]/a[contains(@href, 'ISO')]") 
name_col <- html_nodes(tab, xpath=".//td[2]") 

data_frame(
    iso2c = html_text(iso_col), 
    iso2c_link = html_attr(iso_col, "href"), 
    country_name = html_text(name_col), 
    country_link = html_nodes(name_col, xpath=".//a[contains(@href, 'wiki')]") %>% html_attr("href") 
) 
## # A tibble: 249 x 4 
## iso2c   iso2c_link   country_name    country_link 
## <chr>    <chr>    <chr>      <chr> 
## 1 AD /wiki/ISO_3166-2:AD    Andorra    /wiki/Andorra 
## 2 AE /wiki/ISO_3166-2:AE United Arab Emirates /wiki/United_Arab_Emirates 
## 3 AF /wiki/ISO_3166-2:AF   Afghanistan   /wiki/Afghanistan 
## 4 AG /wiki/ISO_3166-2:AG Antigua and Barbuda /wiki/Antigua_and_Barbuda 
## 5 AI /wiki/ISO_3166-2:AI    Anguilla    /wiki/Anguilla 
## 6 AL /wiki/ISO_3166-2:AL    Albania    /wiki/Albania 
## 7 AM /wiki/ISO_3166-2:AM    Armenia    /wiki/Armenia 
## 8 AO /wiki/ISO_3166-2:AO    Angola    /wiki/Angola 
## 9 AQ /wiki/ISO_3166-2:AQ   Antarctica   /wiki/Antarctica 
## 10 AR /wiki/ISO_3166-2:AR   Argentina   /wiki/Argentina 
## # ... with 239 more rows 
+0

谢谢!对不起,我认为评论会足够好,将来会尝试着提供更多信息! –