0

The Rselenium code below comes from the answer/comment to the this SO post. Sample code is there.

option <- remDr$findElement(using = 'xpath', "//select[@id='main_ddYear']/option[@value='2014']")
option$clickElement()

Note the literal '2014' near the end of the first line.

Can a variable be used in place of the literal '2014'? E.g.,

var1 = "2014"
option <- remDr$findElement(using = 'xpath', "//select[@id='main_ddYear']/option[@value= var1 ]")

I've tried just using the variable var1.

Also tried braces {} inside and outside of single quotes (') {var1}, '{var1}', {'var1'}, which were ideas from other posts.

Similarly, I tried using plus signs as suggested in a similar post on how to pass variables to strings in Java. E.g., + var1 +, +var+, '+var1+'.

Community
  • 1
  • 1
LWRMS
  • 547
  • 8
  • 18
  • You can just paste it. `var1 = "2014"; u <- paste("//select[@id='main_ddYear']/option[@value=", var1," ]"); option <- remDr$findElement(using = 'xpath', u)` – Chrisss Sep 29 '16 at 03:58
  • 1
    whoops, I'm guessing you still need the single quotes so... `u <- paste("//select[@id='main_ddYear']/option[@value=", sQuote(var1)," ]");` – Chrisss Sep 29 '16 at 04:05
  • 1
    CSS selectors and XPath are two completely different things. They aren't two names for the same thing. If you're looking for a general term, you're probably thinking of "locator". – BoltClock Sep 29 '16 at 05:14
  • @BoltClock - I meant to insert the CSS expression from the comment in the referenced post `remDr$findElement("css", "#main_ddYear option[value='2014']")`. I mistakenly inserted the xpath expression from the answer. – LWRMS Sep 29 '16 at 16:45

1 Answers1

1

Your XPath expression is just a string in , so you should be able to use any approach for string concatenation or interpolation :

var1 = "2014"

option <- remDr$findElement(using = 'xpath', paste("//select[@id='main_ddYear']/option[@value='", var1, "']"))
option <- remDr$findElement(using = 'xpath', sprintf("//select[@id='main_ddYear']/option[@value='%s']", var1))

As an aside, it is also possible to compare the value 2014 as number in XPath, by removing the surrounding quotes :

option <- remDr$findElement(using = 'xpath', paste("//select[@id='main_ddYear']/option[@value=", var1, "]"))
option <- remDr$findElement(using = 'xpath', sprintf("//select[@id='main_ddYear']/option[@value=%s]", var1))
Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
  • And for future searchers, the method also works perfectly for `using = css', along the same lines. – LWRMS Sep 29 '16 at 17:05