XPath表达式无效报错求助:Document的evaluate方法执行失败
Hey there, let's break down why your XPath is throwing that syntax error and get it working properly. There are two key issues with your current expression, plus a handy optimization you might want to use:
1. Case Sensitivity for XPath Axes
XPath is strict about case when it comes to axis names. You wrote Parent::div with a capital "P" — this is invalid. All axis names (like parent, following-sibling, child) must be lowercase. That's one major reason the evaluate method is rejecting your expression.
2. Quote Conflicts (If Using in JavaScript)
Looking at the error message, your full XPath string is wrapped in single quotes. Inside that, you have text()='First Name' which also uses single quotes. This causes the string to terminate early in JavaScript, leading to a syntax error. To fix this, you can either:
- Swap the inner single quotes for double quotes, or
- Wrap the entire XPath expression in double quotes instead.
Corrected XPath Expressions
Pure XPath (e.g., browser console, testing tools)
//label[text()='First Name']/parent::div/following-sibling::div/div/input[@disabled='disabled']
For JavaScript Use (avoiding quote clashes)
Option 1: Use double quotes inside the expression
document.evaluate("//label[text()=\"First Name\"]/parent::div/following-sibling::div/div/input[@disabled='disabled']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
Option 2: Wrap the whole expression in double quotes
document.evaluate('//label[text()="First Name"]/parent::div/following-sibling::div/div/input[@disabled="disabled"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
Bonus Optimization
For boolean attributes like disabled, you don't need to check for a specific value. Simply using @disabled will match any element that has the attribute (regardless of its value, which is often just disabled or empty in HTML). This makes your expression cleaner:
//label[text()='First Name']/parent::div/following-sibling::div/div/input[@disabled]
Quick Troubleshooting Tip
If the expression still doesn't find your element after fixing syntax issues, check if the <label> has extra whitespace around "First Name". You can use normalize-space() to ignore leading/trailing spaces and line breaks:
//label[normalize-space(text())='First Name']/parent::div/following-sibling::div/div/input[@disabled]
内容的提问来源于stack exchange,提问作者ramachandran R

