为 R 脚本识别 url 的正确 CSS 选择器

identify the correct CSS selector of a url for an R script

我正在尝试从网站获取数据,多亏了帮手,我可以访问以下脚本:

require(httr)
require(rvest)
      res <- httr::POST(url = "http://apps.kew.org/wcsp/advsearch.do", 
                    body = list(page = "advancedSearch", 
                                AttachmentExist = "", 
                                family = "", 
                                placeOfPub = "", 
                                genus =      "Arctodupontia", 
                                yearPublished = "", 
                                species ="scleroclada", 
                                author = "", 
                                infraRank = "", 
                                infraEpithet = "", 
                                selectedLevel = "cont"), 
                    encode = "form") 
  pg <- content(res, as="parsed")
  lnks <- html_attr(html_node(pg,"td"), "href")

但是,在某些情况下,如上面的示例,它不会检索到正确的 link,因为出于某种原因,html_attr 在其中找不到 url ("href") html_node 检测到的节点。到目前为止,我尝试了不同的 CSS 选择器,例如 "td"、"a.onwardnav" 和“.plantname”,但其中 none 生成了一个 html_attr 可以处理的对象正确。 有什么提示吗?

您真的很接近得到您期望的答案。如果您想从所需页面中拉出链接,则:

lnks <- html_attr(html_nodes(pg,"a"), "href") 

将 return 具有 "href" 属性的 "a" 标签中所有链接的列表。注意命令是 html_nodes 而不是节点。有多个 "a" 标签,因此是复数。
如果您要从正文中的 table 中查找信息,请尝试以下操作:

html_table(pg, fill=TRUE)
#or this
html_nodes(pg,"tr")

第二行将 return 来自 table 的 9 行的列表,然后可以对其进行解析以获取行名称 ("th") and/or 行值 ("td").
希望这有帮助。