VB.NET/C#.NET MSHTML:无法获取“”;name”;在使用“;setAttribute(';nam
本文关键字:NET setAttribute nam name 获取 VB MSHTML | 更新日期: 2023-09-27 18:00:24
我正在开发一个所见即所得应用程序,专门用于我公司的使用,并与公司现有工具进行自定义集成。
当我试图使用".OuterHtml"获取html字符串时,无法从某些元素中获取"name"属性,尤其是INPUT标记元素。
代码示例:
`Dim inElem as windows.forms.htmlElement = hdoc.CreateElement("INPUT")`
`inElem.Id = "txt01"`
`inElem.setAttribute("name", inElem.Id)`
`inElem.setAttribute("type", "text")`
`inElem.setAttribute("placeholder","text here....")`
'' append the created element to html body
`hdoc.Body.AppendChild(inElem)`
--> Getting html string:
** hdoc.body.getElementById("txt01").OuterHtml => "<input id=txt01 placeholder='text here....'></input>"
--> What I really want is:
** hdoc.body.getElementById("txt01").OuterHtml => "<input id=txt01 placeholder='text here....' type='text' name='txt01'></input>"
是的,不仅缺少name属性,还缺少其他一些属性。(例如TYPE)有人能在这件事上帮我吗?
尝试的解决方案:
For Each inputEle As Windows.Forms.HtmlElement In hdoc.Body.GetElementsByTagName("input")
CType(inputEle.DomElement, mshtml.IHTMLInputElement).name = inputEle.Id
Next
**失败**:(
最终解决方案:
Use HTML Agility Pack:
----------------------
Dim inputEle3 As HtmlAgilityPack.HtmlNode = new_wb.CreateElement("input")
inputEle3.Attributes.Add("id", "txt01")
inputEle3.Attributes.Add("name", inputEle3.Id)
inputEle3.Attributes.Add("type", "text")
inputEle3.Attributes.Add("placeholder", "text here ....")
RESULT:
-------
inputEle3.OuterHtml => <input id="txt01" name="txt01" type="text" placeholder="text here ...." >
如果我使用HtmlAgilityPack.dll,它现在可以工作了:(Microsoft mshtml糟透了!:(
这就是我的工作原理。请原谅我使用dynamic
数据类型,由于某种原因,我的Visual Studio上没有mshtml
库。
private void Form1_Load(object sender, EventArgs e)
{
this.webBrowser1.Navigate("about:blank");
this.webBrowser1.Document.Write("<INPUT id='hell' class='blah' placeholder='text here' name='hell' type='text'></INPUT>");
dynamic htmldoc = webBrowser1.Document.DomDocument as dynamic;
dynamic node = htmldoc.getElementById("hell") as dynamic;
string x = node.OuterHtml; //gets name but not type
string s = node.GetAttribute["type"]; //gets type
string name = node.GetAttribute["name"]; //gets name
}
因此OuterHtml-per-say没有获得属性,但在调用GetAttribute方法时,它确实起了作用。希望这能有所帮助。
终极解决方案:
Use HTML Agility Pack:
----------------------
Dim inputEle3 As HtmlAgilityPack.HtmlNode = new_wb.CreateElement("input")
inputEle3.Attributes.Add("id", "txt01")
inputEle3.Attributes.Add("name", inputEle3.Id)
inputEle3.Attributes.Add("type", "text")
inputEle3.Attributes.Add("placeholder", "text here ....")
RESULT:
-------
inputEle3.OuterHtml => <input id="txt01" name="txt01" type="text" placeholder="text here ...." >
如果我使用HtmlAgilityPack.dll,它现在就可以工作了:(Microsoft mshtml糟透了!:(