如何单击没有ID的网页上的按钮?

问题描述:

如果您导航到 此网站 ,您会看到有一个ExportExcel按钮.如果我查看源代码,我会找到以下格式的按钮:

If you navigate to this website, you can see there is an ExportExcel button. If I view source, I find the button under this format:

<td align="right" class="ExportExcel" valign="middle">                                    
    <a href="JavaScript:void(0)" onClick="openExport('../pages/ListExportToExcel.aspx?zipCode=&city=&county=&sState=MI&fromPrice=0&toPrice=0&fCaseNumber=&bed=0&bath=0&street=&buyerType=0&specialProgram=&Status=0&indoorAmenities=&outdoorAmenities=&housingType=&stories=&parking=&propertyAge=');return false;" >Export to</a>
</td>

遵循 此解决方案 > :

WebBrowser MyBrowser = new WebBrowser();
MyBrowser.Navigate("https://www.hudhomestore.com/Listing/PropertySearchResult.aspx?sState=MI");
HtmlElementCollection classButton = MyBrowser.Document.All;
foreach (HtmlElement element in classButton)
    if (element.GetAttribute("ExportExcel") == "button")
        element.InvokeMember("click");

由于MyBrowser.Document为空,我得到了一个错误:

I am getting an error as MyBrowser.Document is null:

对象引用未设置为对象的实例.

Object reference not set to an instance of an object.

我要去哪里错了?还是有更好/不同的方式?

Where am I going wrong? Or is there a better / different way?

基于s

Based on the suggestion by user @DavidR, I have tried the below but MyBrowser_DocumentCompleted never gets any hits:

public partial class mainForm : Form
{
    WebBrowser MyBrowser = new WebBrowser();

    // ..

    private void mainForm_Load(object sender, EventArgs e)
    {
        MyBrowser.Navigate("https://www.hudhomestore.com/Listing/PropertySearchResult.aspx?sState=MI");
    }

    void MyBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        HtmlElementCollection classButton = MyBrowser.Document.All;
        foreach (HtmlElement element in classButton)
            if (element.GetAttribute("ExportExcel") == "button")
                element.InvokeMember("click");
    }

}

获取所有Anchor tags并找到您想要单击的所需tag.我已经编写了代码,请尝试一下.

Get all the Anchor tags and find your required tag which you want to click. I've made a code, try this out.

        HtmlElementCollection links = MyBrowser.Document.GetElementsByTagName("A");
        foreach (HtmlElement link in links)
        {
            if (link.InnerText!=null && link.InnerText.Equals("Export to"))
                link.InvokeMember("Click");
        }

希望有帮助.