0
<div style="padding: 4px 15px; background-color: rgb(212, 208, 200); color: rgb(0, 0, 0);" onmouseover="hl(this,true);" onmouseout="hl(this,false);" onclick="select_menu('1','doc_107094');">Download...</div></div>

I'm trying to click the onclick event and match until select_menu('1' with code

FindElement(By.XPath("//div[starts-with(@onclick 'select_menu('1'')]"));

and my error

OpenQA.Selenium.InvalidSelectorException: 'Given xpath expression "//div[starts-with(@onclick 'select_menu('1'')]" is invalid: SyntaxError: The expression is not a legal expression.'
Guy
  • 46,488
  • 10
  • 44
  • 88
jesintha roselin
  • 171
  • 1
  • 15

2 Answers2

1

Use escaped double quotes around the onclick value

FindElement(By.XPath("//div[starts-with(@onclick, \"select_menu('1'\")]");
Guy
  • 46,488
  • 10
  • 44
  • 88
0

This error message...

OpenQA.Selenium.InvalidSelectorException: 'Given xpath expression "//div[starts-with(@onclick 'select_menu('1'')]" is invalid: SyntaxError: The expression is not a legal expression.'

...implies that the xpath expression was not a valid one.


Reason

When dealing with xpath the ( and ' characters are part of the syntax. So you need to exclude them or escape them.


Solution

To locate element by partial onclick event attribute you can use the following xpath based Locator Strategies:

  • xpath using starts-with():

    FindElement(By.XPath("//div[starts-with(@onclick, 'select_menu')]"));
    
  • xpath using starts-with() and contains():

    FindElement(By.XPath("//div[starts-with(@onclick, 'select_menu') and contains(@onclick, 'doc')]"));
    
  • xpath using the entire value within onclick event:

    FindElement(By.XPath("//div[@onclick=\"select_menu('1','doc_107094');\"]"));
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352