使用jsoup从其他div/id类中的类中提取href [英] Extracting href from a class within other div/id classes with jsoup
问题描述
您好,我试图从以下来源中提取"title"类中的第一个href(来源仅是整个页面的一部分,但是我正在使用整个页面):
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&qid=1316504574&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&qid=1316504574&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> - 2 Apr 2009)</span>
</div>
我尝试了选择函数和getElementByClass的几种变体,但都给了我一个空"值,例如:
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.
推荐答案
CSS选择器div.title
返回<div class="title">
,而不是您认为的链接.如果需要<a class="title">
,则应使用a.title
选择器.
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");
// ...
或者如果<a class="title">
可以在此之前出现在<div class="title">
之外的文档中的其他地方,则您需要以下更具体的选择器:
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");
// ...
这将返回第一个<a class="title">
,它是<div class="title">
的子代.
This will return the first <a class="title">
which is a child of <div class="title">
.
这篇关于使用jsoup从其他div/id类中的类中提取href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!