R 中 URLencode 的问题

Tom*_*ers 3 r urlencode gsub

为了能够从 RI 访问 NIST Chemistry Webbook 数据库,需要能够将一些查询传递到 URL 编码的网址。大多数情况下,这种转换与 URLencode() 一起工作得很好,但在某些情况下则不然。例如失败的一种情况是

query="Poligodial + 3-methoxy-4,5-methylenedioxyamphetamine (R,S) adduct, # 1"
Run Code Online (Sandbox Code Playgroud)

我试图使用

library(XML)
library(RCurl)
url=URLencode(paste0('http://webbook.nist.gov/cgi/cbook.cgi?Name=',query,'&Units=SI'))
doc=htmlParse(getURL(url),encoding="UTF-8")
Run Code Online (Sandbox Code Playgroud)

但是,如果您在网络浏览器中尝试此网址http://webbook.nist.gov/cgi/cbook.cgi?Name=Poligodial%20+%203-甲氧基-4,5-亚甲基二氧苯丙胺%20(R, S)% 20adduct,%20%23%201&Units=SI 它给出了未找到的名称。显然,如果您尝试从http://webbook.nist.gov/chemistry/name-ser.html进行查询, 则需要 URL 编码的字符串

"http://webbook.nist.gov/cgi/cbook.cgi?Name=Poligodial+%2B+3-methoxy-4%2C5-methylenedioxyamphetamine+%28R%2CS%29+adduct%2C+%23+1&Units=SI"
Run Code Online (Sandbox Code Playgroud)

有没有人知道gsub在这种情况下我应该使用什么样的规则来获得相同类型的 URL 编码?或者有其他简单的解决方法吗?

我试过

url=gsub(" ","+",gsub(",","%2C",gsub("+","%2B",URLencode(paste('http://webbook.nist.gov/cgi/cbook.cgi?Name=',query,'&Units=SI', sep="")),fixed=T),fixed=T),fixed=T)
Run Code Online (Sandbox Code Playgroud)

但这仍然不太正确,我不知道网站所有者可以使用什么规则......

Ric*_*ton 5

URLencode遵循RFC1738 规范(参见第 3 页的第 2.2 节),其中指出:

只有字母数字、特殊字符“$-_.+!*'(),”和用于其保留目的的保留字符可以在 URL 中未编码地使用。

也就是说,它不编码加号、逗号或括号。所以它生成的 URL 理论上是正确的,但实际上却不是。

Scott 提到GEThttr包中的函数调用curlEscapefrom RCurl,它对这些标点字符进行编码。

GET调用handle_url哪个调用modify_url哪个调用build_url哪个调用curlEscape。)

它生成的网址是

paste0('http://webbook.nist.gov/cgi/cbook.cgi?Name=', curlEscape(query), '&Units=SI')
## [1] "http://webbook.nist.gov/cgi/cbook.cgi?Name=Poligodial%20%2B%203%2Dmethoxy%2D4%2C5%2Dmethylenedioxyamphetamine%20%28R%2CS%29%20adduct%2C%20%23%201&Units=SI"
Run Code Online (Sandbox Code Playgroud)

似乎工作正常

httr有很好的功能,你可能想开始使用它。你的代码的最小变化把事情的工作很简单,就是掉URLencodecurlEscape