获取html元素的属性
本文关键字:属性 元素 html 获取 | 更新日期: 2023-09-27 18:11:15
我有这段代码
<button value="1" class="_42ft _4jy0 _n6m _4jy3 _517h _51sy" data-hover="tooltip" aria-label="Start a video call with Tsiato" type="submit" id="js_rk"><i class="_e0b img sp_qk8sNUxukfD sx_4816f8"></i></button>
我正在尝试访问"aria-label",看看它是否包含单词"Start"…
使用此代码
try
{
HtmlElementCollection buttons = pinger.Document.GetElementsByTagName("button");
foreach (HtmlElement curElement in buttons)
{
if (curElement.GetAttribute("classname").ToString() == "_42ft _4jy0 _n6m _4jy3 _517h _51sy")
{
if (curElement.GetAttribute("aria-label").ToString().Contains("Start a video call"))
{
label5.Text = "online";
}
}
}
} catch (NullReferenceException b)
{
Console.WriteLine(b.ToString());
}
我可以找到类,但我不能得到属性"aria-label",看看它是否包含任何"开始"文本…你能告诉我出了什么问题吗?: '
因此,如果有一个按钮不包含aria-label作为属性,您将获得nullreference异常,因为您正在使用Contains()方法对null。
那么试试这个:
String ariaLabel = curElement.GetAttribute("aria-label");
if (ariaLabel != null && ariaLabel.Length != 0)
{
if(ariaLabel.Contains("Start a video call"))
{
// do your stuff
}
}
你可以试试这个-
var p = "<button value='1' class='_42ft _4jy0 _n6m _4jy3 _517h _51sy' data-hover='tooltip' aria-label='Start a video call with Tsiato' type='submit' id='js_rk'><i class='_e0b img sp_qk8sNUxukfD sx_4816f8'></i></button>";
var k = new XmlDocument();
k.Load(new MemoryStream(Encoding.UTF8.GetBytes(p.ToCharArray())));
Console.WriteLine(k.GetElementsByTagName("button")[0].Attributes["aria-label"].Value);
- 你的class=属性的名称是class,而不是classname。
-
如果你的方法GetAttribute(string)可以返回null,你应该总是检查返回值
if (curElement.GetAttribute("classname") == "_42ft _4jy0 _n6m _4jy3 _517h _51sy" && (curElement.GetAttribute("aria-label") ?? "").Contains("Start a video call")) { label5.Text = "online"; }