2014-11-24 52 views
2

我對R很熟練,但對javaScript和其他語言完全無知。我想訪問此公開數據集的信息(http://fyed.elections.on.ca/fyed/en/form_page_en.jsp)。特別是,我在數據框中列出了數千種形式的郵政編碼('A1A1A1')。我想將這些郵政編碼提交到本網站,然後提取返回的選區名稱。 RSelenium看起來很理想,但我無法弄清楚如何讓JavaScript工作。 我正在使用R 3.0.3和RSelenium_1.3的Mac OS 10.9.5。 Firefox是v.33,Selenium是2.44。以下腳本起作用。RSelenium和Javascript

require(RSelenium) 
checkForServer() 
startServer() 
remDr<-remoteDriver() 
remDr$open() 
remDr$getStatus() 
remDr$navigate("http://fyed.elections.on.ca/fyed/en/form_page_en.jsp") 

#After inspecting the source code, you can see the input box has the id 'pcode', for postal code 
webElem<-remDr$findElement(using = 'id', value = "pcode") 
webElem$getElementAttribute('id') 

#This is where I am stuck 
remDr$executeScript(script='arguments[0].click(m1p4v4)', list(webElem)) 

#Utlimately, I have a list of several thousand postal codes, so I would like to create a loop  through to extract all the district names that are stored on the pages that are returned with a successful javascript (see previous command). Three real postal codes that return results are as follows: 
p.codes<-c('m1p4v4', 'n3t2y3', 'n2h3v1') 

我覺得我只是不明白必要的JavaScript命令或執行此腳本的executeScript語法。我會很感激任何幫助。

回答

3

你不需要在這裏使用executeScript

require(RSelenium) 
checkForServer() 
startServer() 
remDr<-remoteDriver() 
remDr$open() 
remDr$getStatus() 
remDr$navigate("http://fyed.elections.on.ca/fyed/en/form_page_en.jsp") 

p.codes<-c('m1p4v4', 'n3t2y3', 'n2h3v1') 
webElem<-remDr$findElement(using = 'id', value = "pcode") 
webElem$sendKeysToElement(list(p.codes[1])) # send the first post code to the element 

remDr$findElement("id", "en_btn_arrow")$clickElement() # find the submit button and click it 

,如果你想使用executeScript而是你將與替換最後一行:

remDr$executeScript("arguments[0].click();" 
       , list(remDr$findElement("id", "en_btn_arrow"))) 

executeScript需要一個腳本作爲參數和名單。如果列表中的任何元素的類別爲 webElement,那麼它們可以像DOM元素一樣在腳本中引用。在這種情況下,第一個元素(JavaScript中的零索引)是webElement,我們要求在JavaScript中單擊它。

而且如果檢查按鈕後面的源代碼時,按下它調用document.pcode.submit()這樣更簡單地在這種情況下,如果你想使用executeScript你可以做,你會發現:

remDr$executeScript("document.pcode.submit();")