Xpath tools: Difference between revisions

Jump to navigation Jump to search
2,069 bytes added ,  Yesterday at 13:54
Line 21: Line 21:
</table>
</table>


== Browser console ==
== Browser Console ==


Browser console of {{chrome}} or {{Edge}}
=== List matched elements by XPath rule ===
# 選單: 工具 -> 開發人員工具 -> Console
 
# 確認符合 XPath 規則的結果,例如 XPath 規則是 {{kbd | key = <nowiki>"//img"</nowiki>}},可在 Console 輸入 {{kbd | key = <nowiki> $x("//img") </nowiki>}},按 Enter。就會顯示符合 xpath 規則的結果<ref>[http://stackoverflow.com/questions/3030487/is-there-a-way-to-get-the-xpath-in-google-chrome Is there a way to get the xpath in google chrome? - Stack Overflow]</ref><ref>[https://yizeng.me/2014/03/23/evaluate-and-validate-xpath-css-selectors-in-chrome-developer-tools/ Evaluate and validate XPath/CSS selectors in Chrome Developer Tools | Yi Zeng’s Blog]</ref>
Open the browser console in {{chrome}} or {{Edge}}:
 
# Menu: Tools → Developer Tools → Console
# To verify elements matching an XPath rule, type the expression using $x(). For example, to find all images, enter {{kbd | key = <nowiki>$x("//img")</nowiki>}} and press Enter. The matched elements will be listed in the console<ref>[http://stackoverflow.com/questions/3030487/is-there-a-way-to-get-the-xpath-in-google-chrome Is there a way to get the xpath in google chrome? - Stack Overflow]</ref><ref>[https://yizeng.me/2014/03/23/evaluate-and-validate-xpath-css-selectors-in-chrome-developer-tools/ Evaluate and validate XPath/CSS selectors in Chrome Developer Tools | Yi Zeng's Blog]</ref>:


https://planetoid.info/images/xpath_result_on_browser_console.jpg
https://planetoid.info/images/xpath_result_on_browser_console.jpg


擷取指定 XPath 的元素文字,清理後以換行分隔顯示。下方例子的 XPath 規則是 {{kbd | key = <nowiki>//div[@id="showvender"]/a</nowiki>}}
To extract and display the text content of matched elements — cleaned and separated by newlines — use the snippet below. The example uses XPath rule {{kbd | key = <nowiki>//div[@id="showvender"]/a</nowiki>}}:
<pre>
<pre>
// 使用 document.evaluate 取得所有元素
// Use document.evaluate to retrieve all matching elements
const result = document.evaluate('//div[@id="showvender"]/a', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
const result = document.evaluate('//div[@id="showvender"]/a', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);


// 建立陣列來存放所有元素的文字
// Collect text content from each element
const textArray = [];
const textArray = [];
// 遍歷所有元素
for (let i = 0; i < result.snapshotLength; i++) {
for (let i = 0; i < result.snapshotLength; i++) {
     const element = result.snapshotItem(i);
     const element = result.snapshotItem(i);
     // 去除換行符號並加入陣列
     // Strip newlines and trim whitespace
     const cleanedText = element.textContent.replace(/[\n\r]+/g, '').trim();
     const cleanedText = element.textContent.replace(/[\n\r]+/g, '').trim();
     textArray.push(cleanedText);
     textArray.push(cleanedText);
}
}


// 用換行符號連接所有元素
// Print all results, one per line
console.log(textArray.join('\n'));
</pre>
 
 
=== List matched elements by CSS selector ===
 
To quickly list all elements matching a CSS selector, use {{kbd | key = <nowiki>$$("css-selector")</nowiki>}} in the console. For example, to find all images, enter {{kbd | key = <nowiki>$$("img")</nowiki>}} and press Enter. The matched elements will be listed in the console.
 
To extract and display the text content of matched elements — cleaned and separated by newlines — use the snippet below. The example uses CSS selector {{kbd | key = <nowiki>div#showvender a</nowiki>}}:
<pre>
// Use querySelectorAll to retrieve all matching elements
const elements = document.querySelectorAll('div#showvender a');
 
// Collect text content from each element
const textArray = [];
elements.forEach(el => {
    // Strip newlines and trim whitespace
    const cleanedText = el.textContent.replace(/[\n\r]+/g, '').trim();
    textArray.push(cleanedText);
});
 
// Print all results, one per line
console.log(textArray.join('\n'));
console.log(textArray.join('\n'));
</pre>
=== Highlight matched elements by XPath rule ===
By XPath rule:
<pre>
const xpath = '//main[contains(@class, "htmlview") and @data-cat="article"]';
// Helper: resolve XPath to an array of elements
function $x(xpath) {
  const result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  return Array.from({ length: result.snapshotLength }, (_, i) => result.snapshotItem(i));
}
// Scroll to the first matched element
$x(xpath)[0]?.scrollIntoView();
// Highlight all matched elements with a red outline
$x(xpath).forEach(el => {
  el.style.outline = '3px solid red';
});
</pre>
=== Highlight matched elements by CSS selector ===
By CSS selector:
<pre>
const cssSelector = "main.htmlview[data-cat='article']";
// Scroll to the first matched element
document.querySelector(cssSelector)?.scrollIntoView();
// Highlight all matched elements with a red outline
document.querySelectorAll(cssSelector).forEach(el => {
  el.style.outline = '3px solid red';
});
</pre>
</pre>


Navigation menu