我有一个动态生成的HTML表单。我可以在Php + cURL中管理编码以自动登录任何网站。但是,在这种情况下,表单字段名称每次加载表单时都会更改。
我想知道在加载表单后是否有办法获取表单字段名称。之后,我可以使用表单字段名称进一步操作。
你不必局限于Php,但最好是。
答案 0 :(得分:3)
我会在DOMDocument对象中加载页面,然后使用带有'form'的getElementByTagName来获取页面中的每个表单节点。然后,您可以遍历每个表单字段名称。
以下是一些代码供您启动,如果您知道表单的名称属性或其他内容,将会有所帮助。因为getElementsByTagName将返回页面上的每个表单标记。
// Create a new DOM Document to hold our webpage structure
$xml = new DOMDocument();
// Load the html's contents into DOM
@$xml->loadHTML($html);
// get each form in a DOMNodeList
$forms = $xml->getElementsByTagName('form');
foreach ($forms as $form) {
// if you know the form name attribute, you could check it here before continuing...
// with $form->getAttribute('name'), and the continue with next iteration if not the right one
// loop throught each input tags in the form
$inputs = $form->getElementsByTagName('input');
foreach ($inputs as $input) {
// get input name attribute and value and ...
$inputName = $input->getAttribute('name');
$inputValue = $input->getAttribute('value');
...
}
}
另一种方法是使用Xpath表达式,如下所示:
// Create a new DOM Document to hold our webpage structure
$xml = new DOMDocument();
// Load the html's contents into DOM
@$xml->loadHTML($html);
$oXpath = new DOMXPath($xml);
// will return a DOMNodeList of every input from every forms
$inputs = $oXpath->query("//form//input");
// again , knowing the name attribute of the form is better, you could use:
//$oXpath->query("//form[@name='form_name']//input");
// you would be sure to have the correct inputs in your list
foreach ($inputs as $input) {
//loop through inputs ...
}
如果您尝试从中获取数据的表单是可识别的,通过属性(名称,ID)或被相同类型的父节点包围(即表单始终位于具有固定ID的div,...),在您的源代码中查找这样的模式,我或许可以为您提供正确的Code / Xpath表达式。
答案 1 :(得分:0)
你可以使用katsuo11提到的DOM。以下是可能对您有帮助的示例JS代码。
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += "<b>Type:</b>" + elem[i].type + "  ";
str += "<b>Name:</b>" + elem[i].name + " ";
str += "<b>Value:</b><i>" + elem[i].value + "</i> ";
str += "<BR>";
}
document.getElementById('lblValues').innerHTML = str;
}
</script>