Foreach无法从节点获取xpath结果

时间:2019-11-06 01:33:43

标签: php selenium-webdriver foreach webdriver

我使用xpath webdriver在代码中找到一个div,我需要获取该div的每个节点上的数据,但这没有发生。

HTML:

<div class="elements">
    <div class="element"><div class="title">Title A</div></div>
    <div class="element"><div class="title">Title B</div></div>
    <div class="element"><div class="title">Title C</div></div>
</div>

PHP代码:

$elements = array();
$data = $driver->findElements(WebDriverBy::xpath("//div[@class='elements']//div[@class='element']"));
foreach ($data as $i => $element) {
    $elements[$i]["title"] = $element->findElement(WebDriverBy::xpath("//div[@class='title']"))->getText();
}

返回结果数组$ elements:

Array
(
    [0] => Array
        (
            [title] => Title A
        )

    [1] => Array
        (
            [title] => Title A
        )

    [2] => Array
        (
            [title] => Title A
        )

)

上述脚本仅返回标题A 3次。 我需要它像xPath [x]中的数字一样工作。例子:

(//div[@class='elements']//div[@class='element'])[1]//div[@class='title'](标题A) (//div[@class='elements']//div[@class='element'])[2]//div[@class='title']代表标题B (//div[@class='elements']//div[@class='element'])[3]//div[@class='title']用于标题C

我不能使用数字,因为xPath太大,会使代码混乱很多。

肯定不应该在foreach中使用正确的节点xPath吗?

1 个答案:

答案 0 :(得分:0)

在使用WebElementWebElement来定位另一个xpath时,您需要在路径中使用当前上下文.

$element->findElement(WebDriverBy::xpath(".//div[@class='title']"))