Javascript 如何在selenium中单击自定义属性?

Javascript 如何在selenium中单击自定义属性?,javascript,selenium,xpath,nodes,Javascript,Selenium,Xpath,Nodes,我有以下html: 它有一个类和一个自定义属性,我有几个具有相同类名的头。我想知道如何唯一地获取这个元素并单击它 <h4 class="font-white topic-heading progress-header no-margin width-80 d-table-cell" data-collapse-id="1">I. Introduction</h4> 我还尝试:- var element = driver.findElement(By.xpath("//*

我有以下html: 它有一个类和一个自定义属性,我有几个具有相同类名的头。我想知道如何唯一地获取这个元素并单击它

<h4 class="font-white topic-heading progress-header no-margin width-80 d-table-cell" data-collapse-id="1">I. Introduction</h4>
我还尝试:-

var element = driver.findElement(By.xpath("//*[@data-collapse-id='1']"));

element.click(); // element.click is not a function exception.
我想知道如何获取selenium中的元素并单击它

<h4 class="font-white topic-heading progress-header no-margin width-80 d-table-cell" data-collapse-id="1">I. Introduction</h4>
这是整个部门:

<div class="page-width d-table topic-heading-div">
   <h4 class="font-white topic-heading progress-header no-margin width-80 d-table-cell" data-collapse-id="1">I. Introduction</h4>
   <i class="fa fa-check font-white font-18 width-20 d-table-cell text-center vertical-center" aria-hidden="true"></i>
</div>

一、导言
您是否尝试过:

driver.findElement(By.cssSelector("h4[data-collapse-id='1']")).click();

通过此属性查找元素应该是有效的,因为这是唯一的。此外,它有时无法单击xpath找到的元素。我认为这应该是可行的,因为您的
元素
变量似乎打算返回。然而,该方法应该接收属性名值作为参数,并返回一个简单字符串的属性值。。。这里有几个问题:

  • 您试图传递错误的参数:
    'data-collapse-id=“1”
    而不是
    'data-collapse-id'
  • 属性值是字符串,不可单击

问题的简单答案-您无法单击自定义属性

类用于定义具有类似功能的一组元素。在这种情况下,
主题标题
类用于将
标记与名为
数据折叠ID
的唯一ID属性一起分组。但在这种情况下,我们不能使用ID来标识/指定每个web元素,因为同一类的元素可以是数百/数千

您可以使用以下方法尝试唯一地定位任何标题元素:

var exactHeadingText = "I. Introduction"; // Exact heading By locExactTopicHeading = By.xpath("//h4[contains(@class,'topic-heading') and text()='"+ exactHeadingText + "']"); var partialHeadingText = "Introduction"; // Partial heading By locPartialTopicHeading = By.xpath("//h4[contains(@class,'topic-heading') and contains(text(),'"+ partialHeadingText + "')]"); var exactHeadingText=“I.简介”//准确航向 通过locExactTopiHeading=By.xpath(//h4[contains(@class,'topic-heading')和text()='“+exactHeadingText+”]); var partialHeadingText=“简介”//部分标题 By locpartialtopicheadading=By.xpath(//h4[contains(@class,'topic-heading')和contains(text(),“+partialHeadingText+”)”)”; 理想情况下,您应该将
exactHeadingText/partialHeadingText
作为函数参数/参数传递,以便可以重用代码来获取任何主题标题


然后,您可以使用
findElement()
并对其执行任何操作。

“h4”是一个标题标记,不可单击(据我所知)。下面是什么HTML代码?我在回答中添加了整个div,谢谢。在xpath的末尾添加/I。我相信这会起作用,第一个或第二个的大小写应该是小写的(自动更正):类似这样的东西:var element=driver.findElement(By.xpath(“/*[@data collapse id='1']/I”);