PHP XPath 确定是否选中了复选框?

问题描述

在网站上,它有一个复选框 HTML 代码,如下所示:

<input type="checkBox" name="mycheckBox" id="mycheckBox" value="123" checked="checked">

如何检查复选框是否已通过 xPath 选中?我基本上只想要一个布尔值告诉我 True 如果它被选中。我不确定如何获得这个。

<?PHP

$dom = new DOMDocument();
$content = file_get_content('https://example.com');
@$dom->loadHtml($content);

// Xpath to the checkBox
$xp = new DOMXPath($dom);
$xpath = '//*[@id="mycheckBox"]'; // xPath to the checkBox
$answer = $xp->evaluate('string(' . $xpath . ')');

解决方法

您想多了 XPath。 evaluate() 此处计算 XPath 字符串的结果 - 无需将其转换为要计算的 PHP 表达式。

$dom = new DOMDocument();
$content = '<html><body><input type="checkbox" name="mycheckbox" id="mycheckbox" value="123" checked="checked"></body></html>';
@$dom->loadHtml($content);

// Xpath to the checkbox
$xp = new DOMXPath($dom);
$xpath = '//*[@id="mycheckbox"]'; // xPath to the checkbox
$answer = $xp->evaluate($xpath);

// If we got an answer it'll be in a DOMNodeList,but as we're searching
// for an ID there should be only one,in the zeroth element

if ($answer->length) {
    // Then we need to get the attribute list
    $attr = $answer->item(0)->attributes;

    // now we can check if the attribute exists and what its value is.
    if ($chk = $attr->getNamedItem('checked')) {
        echo $chk = $attr->getNamedItem('checked')->nodeValue;  //checked
    } else {
        echo "No checked attribute";
    }

} else {
    echo "Element with specified ID not found";
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...