2014-11-24 53 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();")