从WebBrowser的HTML元素中获取属性值

本文关键字:获取 属性 元素 WebBrowser HTML | 更新日期: 2023-09-27 18:15:34

我需要括号中的数字,在这种情况下是"14",这样我就可以将其发送到页面上的JavaScript函数提交,或者是否有办法"点击"按钮"当前周"?

<form id="timetablesForm" action="timetablesController.jsp" method="post">
    <p>
        <input type="button" name="Current week" value="Current week" onclick="javascript:void+displayTimetable('14')" />
        <input type="button" name="Next week" value="Next week" onclick="javascript:void+displayTimetable('15')" />
        <input type="button" name="Current semester" value="Semester 1" onclick="javascript:void displayTimetable('7;8;9;10;11;12;13;14;15;16;17;21')" />
    </p>
function displayTimetable(selectdweeks)

我在Windows Phone中工作,所以WebBrowser.Document不可用。我使用下面的脚本以不同的形式设置了一个值:

webBrowser1.InvokeScript("eval", "document.getElementById('loginform1').user.value = 'username';");

我如何从HTML页面获得一个值?我还可以用InvokeScript调用什么函数?如果你能给我一个函数列表,我将不胜感激。

从WebBrowser的HTML元素中获取属性值

使用

webBrowser1.SaveToString()

然后解析HTML以获得我想要的位

下面的代码从第一个输入"Current week"中提取"14":

private void button1_Click(object sender, RoutedEventArgs e)
{
    // first define a new function which returns the content of "onclick" as string
    webBrowser1.InvokeScript("eval", "this.newfunc_getmyvalue = function() { return document.getElementById('Current week').attributes.getNamedItem('onclick').value; }");
    // now invoke the function and save the result (which will be "javascript:void+displayTimetable('14')")
    string onclickstring = (string)webBrowser1.InvokeScript("newfunc_getmyvalue");
    // now split the string at the single quotes (you might have to adapt this parsing logic to whatever string you expect; this is just a simple approach)
    string[] substrings = Regex.Split(onclickstring, "'");
    // this shows a messagebox saying "14"
    MessageBox.Show(substrings[1]);
}

背景:

最初我认为返回一个值应该像:

一样简单:
// ATTENTION: THIS DOESN'T WORK
webBrowser1.InvokeScript("eval", "return 'hello';");

但这总是抛出一个SystemException("一个未知的错误已经发生。错误:80020101.")这就是为什么上面的代码首先定义了一个返回所需值的JavaScript函数的原因。然后我们调用这个函数,结果成功返回。

您是否尝试过这样做,获取值?

Object val = webBrowser1.InvokeScript("eval", "document.getElementById('loginform1').user.value;");