【问题标题】:URL gets truncated with httr::GET vs xmlParseURL 被 httr::GET vs xmlParse 截断
【发布时间】:2015-02-28 11:06:23
【问题描述】:

我正在尝试使用两种不同的方法(xmlParse 和 httr::GET)请求 XML 文档,并期望响应相同。 我使用 xmlParse 得到的响应是我所期望的,但是使用 httr::GET 我的请求 URL 在某些时候会被截断。

一个例子:

require(httr)
require(XML)
require(rvest)

term <- "alopecia areata"
request <- paste0("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/egquery.fcgi?term=",term)  

#requesting URL with XML
xml_response <- xmlParse(request)

xml_response %>%
        xml_nodes(xpath = "//Result/Term") %>%
        xml_text 

这应该返回

[1] "alopecia areata"        

现在是httr

httr_response <- GET(request)
httr_content <- content(httr_response)

httr_content %>%
        xml_nodes(xpath = "//Result/Term") %>%
        xml_text 

返回

[1] "alopecia"

有趣的是:如果我们检查请求 URL 的 httr_response 元素,它是正确的。只有响应是错误的。

> httr_response$request$opts$url

[1] "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/egquery.fcgi?term=alopecia areata"

> httr_response$url

[1] "http://eutils.ncbi.nlm.nih.gov/gquery?term=alopecia&retmode=xml"

所以在某些时候我的查询词被截断了。如果整个请求是手动放入浏览器的,它会按预期运行。

任何解决此问题的建议将不胜感激。

【问题讨论】:

  • 你知道XML 有XPath 函数和xmlValue(),对吧?你真的不需要三个包来获取 xml 文本
  • 是的,但我在其余代码中使用 rvest 函数并且已经习惯了。

标签: xml r httr


【解决方案1】:

您可以尝试将网址中的空格替换为+,以防止其被截断:

httr_response <- GET(gsub(" ","+",request))
httr_content <- content(httr_response)

httr_content %>%
        xml_nodes(xpath = "//Result/Term") %>%
        xml_text 

#[1] "alopecia areata"

关于空间和 URL 的更多信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多