[英]Jsoup element.class.class selcet method returning null
我试图进入<form>
元素内的<form>
<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()
方法中连接这些类。 在select()
方法之后,我的代码以某种方式返回null
。
我的代码:
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个! <button>
元素的类。 那更乱了。
要使用多个类搜索一个元素,必须将多个选择器select("button.btn, button.btn-primary, button.btn-sm")
例如select("button.btn, button.btn-primary, button.btn-sm")
。
有关详细信息,请参阅“ 选择器组合 ”部分中的http://jsoup.org/cookbook/extracting-data/selector-syntax 。
我从没听说过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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.