HtmlAgilityPack 在网站上搜索数组的字符串

HtmlAgilityPack search website for string of an array

我正在编写一个小程序,用于在不同的网站上搜索某些词。如果特定单词不可用或不再可用,我想收到一条错误消息。

我想使代码相对紧凑,因此对 URL 和单词使用数组。

很遗憾,您似乎只能搜索单个字符串:

string checkWord = doc[0].DocumentNode.SelectSingleNode("//*[text()[contains(., 'Word1')]]").InnerText;

// (= no error)

但我想让整个命令循环并使用所有单词的数组而不是 'Word1',这样每个网站都会自动搜索相应的单词: 不幸的是,您似乎只能搜索单个字符串:

string checkWord = doc[i].DocumentNode.SelectSingleNode("//*[text()[contains(., 
        word[i])]]").InnerText;

// (= error)

有谁知道如何在字符串中输入变量(数组)而不是特定文本?

我希望我能够以一种易于理解的方式解释我的问题,并且有人可以帮助我 :)

Ps。整个脚本类似于:

HtmlWeb web = new HtmlWeb();

string[] words = new string[] {"word1", "word2", "word3"};
HtmlDocument[] doc = new HtmlDocument[] {web.Load("www.url1.com"), web.Load("www.url2.com"), web.Load("www.url3.com"),};


for (int i = 0; i < doc.Length; i++)
{
    try()
    {
        string checkWord = doc[i].DocumentNode.SelectSingleNode("//*[text()[contains(., 
        words[i])]]").InnerText;
    }
    catch(Exception)
    {
        Console.WriteLine("Word {0} is not avaiable", i);
        continue;
    }
}

使用 SelectNodes("//text()") 获取所有文本节点,然后在 C# 中返回一个 LINQ 语句来执行包含可能更容易。

例如,此代码将 return 加载页面上存在的所有词:

string[] words = new string[] { "jesse", "jessehouwing", "word3" };
var web = new HtmlWeb();
HtmlDocument[] doc = new HtmlDocument[] { web.Load("https://jessehouwing.net") };


for (int i = 0; i < doc.Length; i++)
{
    var check = doc[i].DocumentNode.SelectNodes("//text()")
        .SelectMany(node => words.Where(word => node.InnerText.Contains(word, StringComparison.CurrentCultureIgnoreCase)))
        .Distinct();
}

结果: