Home > Back-end >  inside my string got " result in The string is not a valid XPath expression
inside my string got " result in The string is not a valid XPath expression

Time:04-03

i want to use xpath expression to click on the dropdownlist and here is my code.

driver.find_element_by_xpath("//select[@name='LocationInspectionId']/option[text()=" '"3" "-D-003-1101_01C03"' "]").click()

my option= 3"-D-003-1101_01C03, and i got error:

SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//select[@name='LocationInspectionId']/option[text()="3"-D-003-1101_01C03"]' is not a valid XPath expression. Can someone help me with this? Thanks.

CodePudding user response:

The text in the option isn't clear to me if it's 3"-D-003-1101_01C03 or "3"-D-003-1101_01C03" (as it appears in the error).

As per the error it is an incorrect XPATH because the quotes are not closed properly:

//select[@name='LocationInspectionId']/option[text()="3"-D-003-1101_01C03"]

I am assuming your html might look something similar to this:

  <select name="LocationInspectionId">
    <option value="1">"34"-D-003-1101_01C03</option>
    <option value="2">"32"-D-003-1101_01C03</option>
    <option value="3">"3"-D-003-1101_01C03</option>
    <option value="4">"43"-D-003-1101_01C03</option>
    <option value="5">"5"-D-003-1101_01C03</option>
  </select>

Now, if you wanted to click on the 3rd option ("3"-D-003-1101_01C03) then you can do this:

driver.find_element(By.XPATH, '//select[@name="LocationInspectionId"]/option[text()=\'"3"-D-003-1101_01C03\']').click()

If the option was "3"-"D-003-1101_01C03", then do this:

driver.find_element(By.XPATH, '//select[@name="LocationInspectionId"]/option[text()=\'"3"-"D-003-1101_01C03"\']').click()

And for 3"-D-003-1101_01C03:

driver.find_element(By.XPATH, '//select[@name="LocationInspectionId"]/option[text()=\'3"-D-003-1101_01C03\']').click()

If the option is just 3-D-003-1101_01C03, then:

driver.find_element(By.XPATH, '//select[@name="LocationInspectionId"]/option[text()="3-D-003-1101_01C03"]').click()

Just make sure you correctly escape (\' or \") the quotes and you'll be fine.

  • Related