Java 如何使用动态生成的名称来操作 html 文本元素?
Java how to manipulate a html text element with dynamic generated name?
我想在网站的 input type="text"
标签中操作或设置文本。但是这个输入在每次加载时都有一个动态生成的名称。
如何获取和操作java中的这个元素?
这是一个例子
<form method="POST" name="sform" class="form-horizontal" role="form" style="text-align: center;">
<input type="text" name="address" class="form-control" style="position: absolute; left: -5000px">
<input type="checkbox" name="honeypot" style="position: absolute; left: -5000px">
<center>
<input type="text" name="VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" class="form-control" value=""
placeholder="Type Text here" style="width: 448px; text-align: center;">
名称 "VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" 出现在每次新加载网站时。
我找不到对这个问题真正有用的帖子。
我应该使用 jsoup 之类的东西吗?
是的,你绝对应该使用 Jsoup。
有了Jsoup,应该就这么简单:
Document doc = Jsoup.connect(url).get();
System.out.println(doc.select("form[name=sform] > center > input").first());
这从 HTML 获取第一个输入元素,它是 form
元素中 centre
元素的子元素。
打印:
<input type="text" name="VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" class="form-control" value="" placeholder="Type Text here" style="width: 448px; text-align: center;">
Jsoup 还提供了许多其他很酷的东西,比如直接获取或设置属性等等。所以你可以这样做:
Element e = doc.select("form[name=sform] > center > input").first();
e.attr("value", "Something");
System.out.println(e);
这将打印:
<input type="text" name="VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" class="form-control" value="Something" placeholder="Type Text here" style="width: 448px; text-align: center;">
值设置为 "Something"。
我想在网站的 input type="text"
标签中操作或设置文本。但是这个输入在每次加载时都有一个动态生成的名称。
如何获取和操作java中的这个元素?
这是一个例子
<form method="POST" name="sform" class="form-horizontal" role="form" style="text-align: center;">
<input type="text" name="address" class="form-control" style="position: absolute; left: -5000px">
<input type="checkbox" name="honeypot" style="position: absolute; left: -5000px">
<center>
<input type="text" name="VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" class="form-control" value=""
placeholder="Type Text here" style="width: 448px; text-align: center;">
名称 "VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" 出现在每次新加载网站时。
我找不到对这个问题真正有用的帖子。
我应该使用 jsoup 之类的东西吗?
是的,你绝对应该使用 Jsoup。
有了Jsoup,应该就这么简单:
Document doc = Jsoup.connect(url).get();
System.out.println(doc.select("form[name=sform] > center > input").first());
这从 HTML 获取第一个输入元素,它是 form
元素中 centre
元素的子元素。
打印:
<input type="text" name="VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" class="form-control" value="" placeholder="Type Text here" style="width: 448px; text-align: center;">
Jsoup 还提供了许多其他很酷的东西,比如直接获取或设置属性等等。所以你可以这样做:
Element e = doc.select("form[name=sform] > center > input").first();
e.attr("value", "Something");
System.out.println(e);
这将打印:
<input type="text" name="VHqnx63SwDau2nuNOOFRM2MCJ5sJawbpHv" class="form-control" value="Something" placeholder="Type Text here" style="width: 448px; text-align: center;">
值设置为 "Something"。