【问题标题】:identify the correct CSS selector of a url for an R script识别 R 脚本的 URL 的正确 CSS 选择器
【发布时间】:2016-08-12 04:13:18
【问题描述】:

我正在尝试从网站获取数据,感谢帮助我可以访问以下脚本:

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")

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

【问题讨论】:

    标签: css r web-scraping rvest httr


    【解决方案1】:

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

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

    将返回带有“href”属性的“a”标签处的所有链接的列表。注意命令是 html_nodes 而不是 node。有多个“a”标签,因此是复数。
    如果您正在查找正文中的表中的信息,请尝试以下操作:

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

    第二行将返回表中 9 行的列表,然后可以对其进行解析以获得行名(“th”)和/或行值(“td”)。
    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多