我正在尝试使用 Jsoup 库的类 FormElement 填写表单。我的问题是它不会更改它提交的 KeyVals 中的值。我在 Jsoup 文档中发现他们是故意这样做的:
public List<Connection.KeyVal> formData()
Get the data that this form submits. The returned list is a copy of the data, and changes to the contents of the list will not be reflected in the DOM.
Returns:
a list of key vals
谁能告诉我如何更改从可用于 FormElement 的方法 formData 检索到的键值列表中的键值。到目前为止,这就是我正在做和得到的,以便您可以更好地理解我:
FormElement form = (FormElement) document.select(form#formulaire).first();
System.out.println(form.formData().get(4).value()); //printing the value of KeyVal #4
form.formData().get(4).value("value changed");//changing its value
System.out.println(form.formData().get(4).value());//printing again its value which must be different
Result:
Old value
Old value
请注意,我知道我可以通过更改 DOM 内每个元素的值来自己完成此操作。但是,我认为这种方式既不是最干净的,也不是最快的。那么有没有办法通过直接更改表单数据中的值来做到这一点?
最佳答案
每次调用方法formData()
通过遍历 DOM 并拉出值来创建新的结果列表。因此,不要继续重新评估该方法。相反,获取引用并从中设置值。例如:
FormElement form = (FormElement) document.select(form#formulaire).first();
List<Connection.KeyVal> formData = form.formData();
System.out.println(formData.get(4).value()); //printing the value of KeyVal #4
form.formData().get(4).value("value changed");//changing its value
System.out.println(form.formData().get(4).value());//printing again its value which must be different
Result:
Old value
value changed
然后,您可以将相同的表单数据传递到新的 post/get 请求中。
我实际上确实希望人们只是更新 DOM。它非常高效,并且更改 formdata 对象中某些内容的值与更改其在 DOM 中的值的效率没有真正的不同,它们都由相同类型的哈希/数组支持。并且没有 HTML 解析或任何东西。
关于java - 通过直接更改 FormData keyVals 的列表 jsoup 来更改 FormElement 的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014643/