我正在尝试访问 <button>
<form>
内的元素元素。
<form action="search.php" method="post" class="form-inline">
<div class="form-group">
<label for="value"><span class="text-uppercase">Lyrics Search:</span></label>
<input type="text" name="value" class="form-control input-sm">
</div>
<div class="form-group">
<select name="field" class="form-control input-sm">
<option value="artist" >Artist</option>
<option value="title" >Title</option>
<option value="body" >Body</option>
</select>
<button type="submit" class="btn btn-primary btn-sm">Submit</button>
</div>
</form>
现在是<button>
元素在 2 HTML
里面类,我知道我需要将这些类连接到 select()
中方法。
不知怎的,我的代码返回 null
select()
之后方法。
我的代码:
HtmlPage htmlPage = new HtmlPage(Jsoup.connect("http://www.lyricsplanet.com/").get());
// Get to <div class="form-group">
Element searchFormElement = htmlPage.getHtmlDocument().select("div.form-group").first();
searchFormElement.attr("name", searchedLyrics); // Setting the value of name to the searched lyrics.
// Getting to <button type="submit" class="btn btn-primary btn-sm">Submit</button>
Element buttonElement = htmlPage.getHtmlDocument().select("button.btn btn-primary btn-sm.form-inline").first();
System.out.println(buttonElement.html());
在 - select("button.btn btn-primary btn-sm.form-inline").first();
我尝试访问<button>
元素使用它是两个类。
那么我做错了什么?
编辑
我刚刚注意到有3个!类(class)到 <button>
元素。那就更乱了。
最佳答案
我从来没有听说过 Jsoup 中有一个名为 HtmlPage 的类。您应该使用 Document 类,如果您调用 Jsoup.connect(...); 将返回该文档类;
您可以尝试以下代码:
Document document = Jsoup.connect("http://www.lyricsplanet.com/").get(); // Just connect
Element formElement = document.select("div#alphabet > form").first(); // Search for form
formElement.select("input[name=value]").val(yourSearchValue); // Set your search value
Element submitButton = formElement.select("button[type=submit]").first(); // Then search in form for submit button, otherwise your selector could find another submit button first
HTML 表单元素(搜索字段和提交按钮)没有可以使用的标识符。唯一的方法是使用这些特定的 css 选择器。
编辑: 您想稍后提交表格吗?那么您就不必搜索提交按钮。您只需在设置搜索值后提交表单即可。尝试以下代码:
Document document = Jsoup.connect("http://www.lyricsplanet.com/").get();
FormElement formElement = document.select("div#alphabet > form").forms().get(0); // Use FormElement instead of Element
formElement.select("input[name=value]").val(yourSearchValue);
Document searchResult = formElement.submit().post(); // Do anything you want with the search result page/html
关于java - Jsoup element.class.class selcet 方法返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36069176/