Extracting href from a class within other div/id classes with jsoup

主宰稳场 提交于 2019-12-25 08:40:02

问题


Hello I am trying to extract the first href from within the "title" class from the following source (the source is only part of the whole page however I am using the entire page):

div id="atfResults" class="list results ">
<div id="result_0" class="result firstRow product" name="0006754023">
    <div id="srNum_0" class="number">1.</div>
        <div class="image">
        <a href="http://www.amazon.co.uk/Essential-Modern-Classics-J-Tolkien/dp/0006754023/ref=sr_1_1?ie=UTF8&amp;qid=1316504574&amp;sr=8-1">
        <img src="http://ecx.images-amazon.com/images/I/31ZcWU6HN4L._AA115_.jpg" class="productImage" alt="Product Details">
</a>
</div>
<div class="data">
    <div class="title">
<a class="title titleHover" href="http://www.amazon.co.uk/Essential-Modern-Classics-J-Tolkien/dp/0006754023/ref=sr_1_1?ie=UTF8&amp;qid=1316504574&amp;sr=8-1">Essential Modern Classics - The Hobbit</a>
        <span class="ptBrand">by J. R. R. Tolkien</span>
 <span class="bindingAndRelease">(<span class="binding">Paperback</span> -&nbsp;2 Apr 2009)</span>
        </div>

I have tried several variations of both the select function and also getElementByClass but all have given me a "null" value such as:

Document firstSearchPage = Jsoup.connect(fullST).get();
Element link = firstSearchPage.select("div.title").first();

If someone could help me with a solution to this problem and recommend some areas of reading so I can avoid this problem in future it would be greatly appreciated.


回答1:


The CSS selector div.title, returns a <div class="title">, not a link as you seem to think. If you want an <a class="title"> then you should use the a.title selector.

Element link = document.select("a.title").first();
String href = link.absUrl("href");
// ...

Or if an <a class="title"> can appear elsewhere in the document outside a <div class="title"> before that point, then you need the following more specific selector:

Element link = document.select("div.title a.title").first();
String href = link.absUrl("href");
// ...

This will return the first <a class="title"> which is a child of <div class="title">.



来源:https://stackoverflow.com/questions/7481930/extracting-href-from-a-class-within-other-div-id-classes-with-jsoup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!