spi*_*tor 4 javascript selenium r web-scraping
我对 R 相当精通,但对 javaScript 和其他语言完全一无所知。我想访问有关此公开数据集的信息(http://fyed.elections.on.ca/fyed/en/form_page_en.jsp)。特别是,我在数据框中有一个包含数千个邮政编码(“A1A1A1”)形式的列表。我想将每个邮政编码提交到该网站,然后提取返回的选区名称。RSelenium 似乎很理想,但我不知道如何让 javascript 工作。我正在使用 Mac OS 10.9.5、R 3.0.3 和 RSelenium_1.3。Firefox 是 v.33,Selenium 是 2.44。以下脚本有效。
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')
Run Code Online (Sandbox Code Playgroud)
我觉得我只是不理解必要的 javascript 命令或执行脚本的语法来完成这项工作。我将不胜感激任何帮助。
您不需要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
Run Code Online (Sandbox Code Playgroud)
如果您想使用executeScript,则可以将最后一行替换为:
remDr$executeScript("arguments[0].click();"
, list(remDr$findElement("id", "en_btn_arrow")))
Run Code Online (Sandbox Code Playgroud)
executeScript接受一个脚本作为参数和一个列表。如果列表中的任何元素属于类
webElement,那么它们可以像 DOM 元素一样在脚本中引用。在本例中,第一个元素(JavaScript 中的零索引)是 a webElement,我们要求在 JavaScript 中单击它。
此外,如果您检查按钮背后的源代码,您会发现当按下按钮时,它document.pcode.submit()会更简单地调用,在这种情况下,如果您想使用,executeScript您可以这样做:
remDr$executeScript("document.pcode.submit();")
Run Code Online (Sandbox Code Playgroud)