【问题标题】:How to click a button on a web page that has no id?如何在没有 id 的网页上单击按钮?
【发布时间】:2017-06-24 08:37:51
【问题描述】:

如果您导航到this website,您会看到有一个ExportExcel 按钮。如果我查看源代码,我会在这种格式下找到按钮:

<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>

关注this solution

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 为空:

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

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

编辑:

基于 suggestion by user @DavidR,我尝试了以下方法,但 MyBrowser_DocumentCompleted 从未获得任何点击:

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");
    }

}

【问题讨论】:

  • 尝试将您的代码包装在 webBrowser.DocumentCompleted 事件中,这将解决此问题。
  • @DavidR 谢谢。你能检查我的编辑吗?
  • 你能设置一个调试点并检查执行是否在那里停止吗?
  • @DavidR 是的,我使用断点进行调试,但我从未遇到过

标签: javascript c# jquery asp.net


【解决方案1】:

获取所有Anchor tags 并找到您想要单击的所需tag。我已经做了一个代码,试试这个。

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

希望对你有帮助。

【讨论】:

  • Adeel 谢谢,但我仍然无法“hit”。 MyBrowser_DocumentCompleted 不执行.. 相同的整个代码是否在您的机器上工作?
  • 我将你的代码添加到mainForm_LoadMyBrowser.Document 仍然为空并弹出错误
  • 我还没有创建WebBrowser控件的实例,我只是将它拖到窗体上,注册事件,就是这样。您应该尝试一下,如果它不起作用,请在此处发表评论。问候!
  • 如果不是 WebBrowser 的实例,那么代码中的 MyBrowser 是什么?
  • 当您将控件拖放到WinForm, Visual Studio 上时,会自动在designer.cs 中创建一个实例。我使用Visual Studio i.e. webBrowser1 分配的默认名称调用了控件
猜你喜欢
  • 1970-01-01
  • 2021-07-05
  • 2020-12-07
  • 2020-01-11
  • 2019-03-25
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
  • 2020-07-28
相关资源
最近更新 更多