如何抓取不同网页上不同xpath的数据?

How to grab a piece of data which has a different xpath on different webpages?

所以我试图抓取一段在不同页面上以不同xpath显示的数据。

如果您将在维基词典上看到 IPA 发音的 xpath...https://en.wiktionary.org/wiki/foo您将看到 xpath 是

//*[@id="mw-content-text"]/ul[1]/li[1]/span[4]

但如果我换一个词,比如 https://en.wiktionary.org/wiki/bar 那么 xpath 将是

//*[@id="mw-content-text"]/ul[1]/li[2]/span[5]

我想不出任何方法来调和这些,我是否遗漏了什么?

答案很简单。永远不要让工具为您编写任何 XPath。所有工具都会出错。

查看文档的 HTML 来源并自己编写适当的 XPath。

var result = document.evaluate("//*[@class = 'IPA']", document),
    elem;

while (elem = result.iterateNext()) { 
    console.log(elem);
}

上面显示的是最简单的变体。它在 https://en.wiktionary.org/wiki/foo and quite a few more on https://en.wiktionary.org/wiki/bar.

上选择了两次 <span class="IPA">

使用更具体的表达式来缩小结果范围。