在 R 中使用用户输入的文本字符串

Using a user input text string in R

我有一个代码可以根据输入的国家/地区使用特定标签从网站中提取数据。但是,我希望它让用户输入一个国家,然后提取适当的详细信息。我的代码如下:

library(rvest)

x <- readline(prompt = "Enter Country:   ")

url <- "http://oceantax.co.uk/links/tax-authorities-worldwide.html"
pg <- html(url)

country <- pg %>% html_nodes(xpath="//a[contains(@title, 'x')]")

country <- pg %>% html_nodes("a[title~=x]")

argname <- country %>% html_text()       # get the text of the anchor
argurl <- country %>% html_attr("href") # get the URL of the anchor
y <- rbind(argname,argurl)

这不起作用,因为 x 在代码中的位置,它不会用用户输入替换它。例如,如果我手动将 x 替换为 Argentina,它就可以完美运行。提前致谢。

原因是 x 被视为引号内的文本。它按字面意思读作字符 "x" 而不是向量。

请参阅下面创建 "formula" 向量的行。我使用 paste() 连接一个字符串,该字符串提供给抓取函数。

这对我有效。让我知道它是否适合你。

library(rvest)

x <- readline(prompt = "Enter Country:   ")

url <- "http://oceantax.co.uk/links/tax-authorities-worldwide.html"
pg <- html(url)

formula<-paste("//a[contains(@title, '",x,"')]",sep='')
country <- pg %>% html_nodes(xpath=formula)

formula<-paste('a[title~=',x,']',sep='')
country <- pg %>% html_nodes(formula)

argname <- country %>% html_text()       # get the text of the anchor
argurl <- country %>% html_attr("href") # get the URL of the anchor
y <- rbind(argname,argurl)

这里有一个仅使用包 XML 的替代方案。此外,这使用 sprintf() 代替 x 的值。当您有多个值可以替换时,这很好,而且它通常比 paste()

更有效
library(XML)

x <- readline(prompt = "Enter Country:   ")
"Argentina"

url <- "http://oceantax.co.uk/links/tax-authorities-worldwide.html"

node <- htmlParse(url)[sprintf("//a[contains(@title, %s)]", x)][[1]]

do.call("rbind", list(argname = xmlValue(node), 
    argurl = xmlGetAttr(node, "href")))

#         [,1]                                       
# argname "Federal Administration of Public Revenues"
# argurl  "http://www.afip.gob.ar/english/"