2014-02-24 43 views
2

爲了能夠從R訪問NIST化學Webbook數據庫,我需要能夠將某些查詢傳遞給URL編碼的Web地址。大多數情況下,這種轉換對URLencode()很有效,但在某些情況下不適用。一例失敗的案例是R中的URLencode問題

query="Poligodial + 3-methoxy-4,5-methylenedioxyamphetamine (R,S) adduct, # 1" 

,我試着用

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

但是如果你在你的網頁瀏覽器 http://webbook.nist.gov/cgi/cbook.cgi?Name=Poligodial%20+%203-methoxy-4,5-methylenedioxyamphetamine%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" 

沒有任何人有任何的想法是什麼樣的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) 

但仍然是不完全正確的,我不知道什麼樣的規則網站的所有者也可以使用...

回答

3

URLencode遵循RFC1738 specification(參見2.2節,第3頁),其中指出:

只有字母數字,特殊字符「$ -_ + !*'(),「和 用於其保留目的的保留字符可以用於在URL中未編碼的 。

也就是說,它不編碼加號或逗號或括號。所以它產生的URL在理論上是正確的,但不是在實踐中。

Scott提到的httr包中的GET函數調用curlEscape來自RCurl,它編碼這些標點符號。

GET調用handle_url它調用modify_url它調用build_url它調用curlEscape。)

它生成的URL是

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" 

seems to work OK

httr有很好的功能,你可能想開始使用它。對代碼進行的最小改動可以讓換成curlEscape

+0

很多謝謝 - 對我來說,這是一個更簡單的解決方案,尤其是因爲我更喜歡getURL()而不是GET()(它對我來說似乎在一些片狀互聯網連接上更健壯一些)! Thx數百萬爲這個很好的解釋! –

1

請問這怎麼辦你要?

library(httr) 
url <- 'http://webbook.nist.gov/cgi/cbook.cgi' 
args <- list(Name = "Poligodial + 3-methoxy-4,5-methylenedioxyamphetamine (R,S) adduct, # 1", 
     Units = 'SI') 
res <- GET(url, query=args) 
content(res)$children$html 

給人

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
    <meta http-equiv="Window-target" content="_top"/> 

...etc. 
+0

哈這好多了,是的 - 非常感謝 - 完全是它應該做的!數百萬! –

+0

真棒,很高興它爲你工作 – sckott