vba Visual Basic:设置不含 ID 的 Web 元素的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19029389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:31:17  来源:igfitidea点击:

Visual Basic: Set attribute of web element whitout ID

vbaelements

提问by CyrielZ

HTML:

HTML:

<input type="text" size="15" maxlength="79" value="" name="username">

As you can see, no ID. The HTML above is a textbox that i want to auto fill in whit my value as soon as i start the webpage whit my code.

如您所见,没有身。上面的 HTML 是一个文本框,我想在我启动包含我的代码的网页后立即自动填充我的值。

this is what i found:

这是我发现的:

WebBrowser1.Document.Forms(0).GetElementsByTagName("username")(0).SetAttribute("value", (Text))

But whit this i get the error:

但是我得到了错误:

Value of '0' is not valid for 'index'. 'index' should be between 0 and -1.
Parameter name: index

What am i doing wrong?

我究竟做错了什么?

回答by David

This isn't going to find any elements:

这不会找到任何元素:

WebBrowser1.Document.Forms(0).GetElementsByTagName("username")

"Tag name" doesn't mean the value of the nameattribute, it means the name of the HTML tag itself. Like this:

“标签名称”并不表示name属性的值,而是表示 HTML 标签本身的名称。像这样:

WebBrowser1.Document.Forms(0).GetElementsByTagName("input")

Of course, this is likely to return multiple matched elements, so you'll need to further identify which one you want to modify. The point being that you should do some error checking to make sure that it finds anything, because trying to index an empty collection will result in an error:

当然,这很可能会返回多个匹配的元素,因此您需要进一步确定要修改的元素。关键是你应该做一些错误检查以确保它找到任何东西,因为尝试索引一个空集合会导致错误:

WebBrowser1.Document.Forms(0).GetElementsByTagName("username")(0)

Since the collection has no elements, there is nothing at index 0.

由于该集合没有元素,因此 index 处没有任何内容0

回答by Sathish Kothandam

May be u could try

也许你可以试试

Me.WebBrowser1.Document.GetElementByName("username").SetAttribute("Value", txtUsername.Text)