使用包含文本的 css 链接元素并访问关联字段

Chaining an element using css containing text and accessing an associated field

我需要访问下面html中的输入字段。页面的设置方式我需要使用 'Address Line 1' 文本进行链接,然后将文本发送到输入字段。输入字段 ID 发生变化,字段的布局也不会根据用户偏好而变化。我在挣扎。如果您需要更多信息,请随时询问我不想提供太多信息。

<td class="labelCol requiredInput">
  <label for="00N36000000xina"><span class="assistiveText">*</span>Address Line 1</label>
</td>
<td class="dataCol col02">
  <div class="requiredInput">
    <div class="requiredBlock"></div>
    <input id="00N36000000xina" maxlength="255" name="00N36000000xina" size="20" tabindex="4" type="text">
  </div>
</td>

我是这样访问的:

element(by.css('div.pbSubsection:nth-child(3) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > input'))

然而,根据用户放置字段的位置,它可以四处移动。所以我希望能够访问标签\并使用它来查明其输入字段。

试试这个:

        List<WebElement> elementList = driver.findElements(By.cssSelector("tbody > tr"));
        for (WebElement element : elementList) {
            if(element.findElement(By.cssSelector("td.labelCol > label")).getText().equalsIgnoreCase("Address Line 1")) {
                element.findElement(By.cssSelector("input[type='text']")).sendKeys("textToInput");
            }
        }

我自己还没有测试过,但你可以尝试这样的事情:

// $ is shorthand for element(by.css())
$('div.assistiveText').getAttribute('for').then(function (val) {

    // locate the <input> by the value of the attribute on <label>
    element(by.id(val)).sendKeys('abc'); // replace sendKeys with your intended function

});

或者,如果标签上的第一个定位符不够具体,请将 $('div.assistiveText') 换成 element(by.cssContainingText('Address Line 1'))

我尝试了它的其他属性(我的应用程序中的任何地方都没有 for 属性),它似乎对我有用。

我不知道量角器,但我拼凑了一些代码,希望可以工作或接近,我会给你思考过程和一些信息,希望你可以用它来修复我的代码,如果需要的话,并解决问题。

首先通过 XPath 查找元素,"//label[text()='Address Line 1']"。这将搜索包含 "Address Line 1" 的 LABEL 标签。找到该元素后,获取 label 属性。根据您的 HTML,这个 label 是您想要的 INPUT 元素的 id。现在使用 id 查找元素并根据需要对其进行处理。

id = element(by.xpath("//label[text()='Address Line 1']")).getAttribute("label")
input = element(by.id(id))
input.sendkeys("some text")