gpt4 book ai didi

c# - 如何将 HtmlAgilityPack 的 Htmlnode 转换为 webbrowser HtmlElement

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:55 26 4
gpt4 key购买 nike

我正在创建一个自动将数据插入 html 输入标签的应用程序。我有用于特定标记的 xPath,例如“/html/body/form/div/div[2]/div/div/input”,我在 HtmlAgilityPack 的帮助下设法获得了 HtmlNode

var documentAsIHtmlDocument3 = (mshtml.IHTMLDocument3)webBrowser.Document.DomDocument;
StringReader sr = new StringReader(documentAsIHtmlDocument3.documentElement.outerHTML);
htmlDocument.Load(sr);
if (htmlDocument.DocumentNode != null)
{
HtmlNode currentNode = htmlDocument.DocumentNode.SelectSingleNode(xPath);
}

现在我需要以某种方式从对应于当前 HtmlNode 的 Webbrowser.Document 中选择 HtmlElement 。有人可以帮我吗?

顺便说一句:我没有创建任何垃圾邮件机器人。

大家好。我找到了递归的解决方案,很多 if 语句但没有 htmlagilitypack,但不幸的是我现在不能发布它。看来我的声望不够。

不过,如果不太费力的话,你能告诉我如何用htmlagilitypack解决这个问题吗,因为我的代码看起来真的很讨厌。

最佳答案

谢谢大家。经过几乎一整天的思考和编程,我决定必须使用原生 htmlElement 而不是 htmlagilitypack HtmlNode,因为我想在 webbrowser 中将文本输入到 Htmlelement 中。所以这是我想出的代码。如果有人用 htmlagilitypack 展示解决方案,我仍然会很感激。

    public HtmlElement selectHtmlNode(string xPath, HtmlElement htmlElement)
{
string currentNode;
int indexOfElement;

//get string representation of current Tag.
if (xPath.Substring(1,xPath.Length-2).Contains('/'))
currentNode = xPath.Substring(1, xPath.IndexOf('/', 1) - 1);
else
currentNode = xPath.Substring(1, xPath.Length-1);
//gets the depth of current xPath
int numOfOccurence = Regex.Matches(xPath, "/").Count;

//gets the children's index
int.TryParse(Regex.Match(currentNode, @"\d+").Value, out indexOfElement);

//if i have to select nth-child ex: /tr[4]
if (indexOfElement > 1)
{
currentNode = currentNode.Substring(0, xPath.IndexOf('[') - 1);
//the tag that i want to get
if (numOfOccurence == 1 || numOfOccurence == 0)
{
return htmlElement.Children[indexOfElement - 1];
}
//still has some children tags
if (numOfOccurence > 1)
{
int i = 1;
//select nth-child
foreach (HtmlElement tempElement in htmlElement.Children)
{
if (tempElement.TagName.ToLower() == currentNode && i == indexOfElement)
{
return selectHtmlNode(xPath.Substring(xPath.IndexOf('/', 1)), tempElement);
}
else if (tempElement.TagName.ToLower() == currentNode && i < indexOfElement)
{
i++;
}
}
}
}
else
{
if (numOfOccurence == 1 || numOfOccurence == 0)
{
return htmlElement.FirstChild;
}
if (numOfOccurence > 1)
{
foreach (HtmlElement tempElement in htmlElement.Children)
{
if (tempElement.TagName.ToLower() == currentNode)
{
return selectHtmlNode(xPath.Substring(xPath.IndexOf('/', 1)), tempElement);
}
}
}
}
return null;
}

函数就是这样调用的。其中 htmlController 是某个类的实例。

HtmlElement currentElement = htmlController.selectHtmlNode("/body/form/div/div[2]/div/div/input", webBrowser.Document.GetElementsByTagName("html")[0]);
currentElement.SetAttribute("Value", "hello world");

关于c# - 如何将 HtmlAgilityPack 的 Htmlnode 转换为 webbrowser HtmlElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10969393/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com