我一直在尝试使用此代码在html / ajax中按类读取元素,因为知道GetElementByClass不是webBrowser.Document中的选项。我似乎无法获得返回值然后调用该成员。有解决方法吗?
参考文献: Getting HTMLElements by Class Name
示例:
<span class="example">(<a href="http://www.test.com/folder/remote/api?=test" onclick=" return do_ajax('popup_fodder', 'remote/api?=test', 1, 1, 0, 0); return false; " class="example">test</a>)</span>
示例代码:
HtmlElementCollection theElementCollection = default(HtmlElementCollection);
theElementCollection = webBrowser1.Document.GetElementsByTagName("span");
foreach (HtmlElement curElement in theElementCollection)
{
//If curElement.GetAttribute("class").ToString = "example" It doesn't work.
// This should be the work around.
if (curElement.OuterHtml.Contains("example"))
{
MessageBox.Show(curElement.GetAttribute("InnerText")); // Doesn't even fire.
// InvokeMember(test) after class is found.
}
}
答案 0 :(得分:13)
我承认这不是很直观,但您需要使用GetAttribute("className")
代替GetAttribute("class")
HtmlElementCollection theElementCollection = default(HtmlElementCollection);
theElementCollection = webBrowser1.Document.GetElementsByTagName("span");
foreach (HtmlElement curElement in theElementCollection)
{
if (curElement.GetAttribute("className").ToString() == "example")
{
MessageBox.Show(curElement.GetAttribute("InnerText")); // Do something you want
}
}
答案 1 :(得分:4)
这是我如何使用webbrowser控件查找特定于类的元素并调用单击内部链接的示例。
简化&gt;
foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("li"))
{
// use contains() if the class attribute is
// class="page_item page-item-218 current_page_item"
//this to be more on spot! >> if (item.OuterHtml.Contains("class=\"page_item"))
// or
if (item.OuterHtml.Contains("page_item"))
{
foreach (HtmlElement childItem in item.Children)
{
if (childItem.TagName == "A")
{
//Click the link/Current element
childItem.InvokeMember("Click");
break;
}
}
break;
}
}
这种方式有效吗?..
这对我有用。
或者我误解了你的问题?
答案 2 :(得分:0)
为什么不使用qjuery的选择器引擎呢? 而且,你期望messagebox.show出现在哪里?
答案 3 :(得分:0)
Dim HtmlElementcolltwo As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("button")
For Each eleme As HtmlElement In HtmlElementcolltwo
' Check the attributtes you want
If eleme.GetAttribute("className") = "derrt_submit feed-zed-bff" Then
'Check even the text if you want
' If elem.InnerText = "Sign In" Then
'Invoke your event
eleme.InvokeMember("click")
'End If
End If
Next
这也适用于而不是使用&#34; class&#34;使用&#34; className&#34;