Selenium Java选择基于嵌套元素文本的div

时间:2019-01-27 07:27:21

标签: selenium selenium-webdriver

我具有以下HTML结构。想要选择标签

的值为3.x

我尝试了以下xpath表达式

$resId = 11;


$counter = 0;
$ids=array(17,34,51,68,85,102,119,136,153,170,187,204,221,238,255,272,289,306,323);

$stmt = $pdo->prepare( 'select * from `lappu` where `resturantid` = :id' );
$stmt->bindParam( ':id', $resId );
$stmt->execute();

$codes=array();

while( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {
    $codes[ $row['resturantid'] ] = $row['code'];
    $counter++;
}








for( $x = 1; $x <= $counter; $x++ ) {
    if ( in_array( $x, $ids ) ) {

        $code=$codes[ $x ];

        for ( $b = 1; $b <= 16; $b++ ) {
            echo 'pictures'.'<br>';
        }

        for ( $b = 1; $b <= 16; $b++ ) {
            echo $code.'<br>';
        } 
    }
}

但是没有用。收到异常"//label[contains(@class='options')]/div/p[contains(text(),'3.x')]" "//div[@class='answerOpts']/label[contains(@class='options')]/div/p[contains(text(),'3.x')]" 。您能告诉我解决方法吗?

HTML结构

org.openqa.selenium.NoSuchElementException: Unable to locate element:

2 个答案:

答案 0 :(得分:1)

尝试在xpath以下

.// div / p [text()='3.x'] / parent :: div / parent :: label / preceding-sibling :: input [1]

答案 1 :(得分:1)

下面是一些xpath示例,您如何获取label元素:

//label[normalize-space(.)='3.x']
//label[contains(@class,'options') and .//p[.='3.x']]
//label[contains(@class,'options') and @for and .//p[.='3.x']]
//p[.='3.x']/ancestor::label[1]
//p[.='3.x']/ancestor::label[contains(@class,'searchable')][1]