Ali*_*Ali 14 c# webbrowser-control getelementsbytagname html-agility-pack
如果我不知道它的id,如何为文本框选择一个元素?
如果我知道它的id,那么我可以简单地写:
HtmlAgilityPack.HtmlNode node = doc.GetElementbyId(id);
Run Code Online (Sandbox Code Playgroud)
但是我不知道textbox的ID,我在HtmlagilityPack中找不到GetElementsByTagName方法,它在webbrowser控件中可用.在Web浏览器控件中我可以简单地写:
HtmlElementCollection elements = browser[i].Document.GetElementsByTagName("form");
foreach (HtmlElement currentElement in elements)
{
}
Run Code Online (Sandbox Code Playgroud)
编辑
这是我正在谈论的HTML表单
<form id="searchform" method="get" action="/test.php">
<input name="sometext" type="text">
</form>
Run Code Online (Sandbox Code Playgroud)
请注意我不知道表格的ID.并且在同一页面上可以有多种形式.我唯一知道的是"sometext",我想用这个名字来获取这个元素.所以我想我必须逐个解析所有表格然后找到这个名字"sometext"但是我该怎么做?
jes*_*ing 32
如果您正在通过其tagName(例如formfor <form name="someForm">)查找标记,那么您可以使用:
var forms = document.DocumentNode.Descendants("form");
Run Code Online (Sandbox Code Playgroud)
如果您正在通过其name属性查找标记(例如someFormfor <form name="someForm">,那么您可以使用:
var forms = document.DocumentNode.Descendants().Where(node => node.Name == "formName");
Run Code Online (Sandbox Code Playgroud)
对于最后一个,您可以创建一个简单的扩展方法:
public static class HtmlNodeExtensions
{
public static IEnumerable<HtmlNode> GetElementsByName(this HtmlNode parent, string name)
{
return parent.Descendants().Where(node => node.Name == name);
}
public static IEnumerable<HtmlNode> GetElementsByTagName(this HtmlNode parent, string name)
{
return parent.Descendants(name);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:您还可以使用SelectNodesXPath来查询文档:
var nodes = doc.DocumentNode.SelectNodes("//form//input");
Run Code Online (Sandbox Code Playgroud)
会在页面上为您提供表单标记中的所有输入.
var nodes = doc.DocumentNode.SelectNodes("//form[1]//input");
Run Code Online (Sandbox Code Playgroud)
将为您提供页面上第一个表单的所有输入
任何节点名称:
doc.DocumentNode.SelectNodes("//*[@name='name']")
Run Code Online (Sandbox Code Playgroud)
按名称输入节点:
doc.DocumentNode.SelectNodes("//input[@name='name']")
Run Code Online (Sandbox Code Playgroud)
我想你正在寻找这样的东西
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml("....");
var inputs = doc.DocumentNode.Descendants("input")
.Where(n => n.Attributes["name"]!=null && n.Attributes["name"].Value == "sometext")
.ToArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29176 次 |
| 最近记录: |