将 jsoup 用于 div 内的 select 标签
Issue using jsoup to select tags within div
我有一个 html 文件,其中包含如下内容:
<div class="title"><a href="../dorothy_perkins_true_blue_suedette/thing?id=130434603" title="Dorothy Perkins True blue suedette clutch bag">Dorothy Perkins True blue suedette clutch bag</a></div>
我想提取 href
中的 url。我有以下代码:
Document doc = Jsoup.connect(url).get();
Elements products = doc.select("div.title a[href]");
System.out.println("size: "+products.size());
打印显示,但是,大小为 0。找不到任何匹配项。我使用的 url 是 http://www.polyvore.com/bags/shop?category_id=35
。你可以看看源代码,我很确定上面的代码是正确的。如果有人可以提供一些想法,那就太好了。非常感谢。
我相信你使用下面的代码来连接。
doc = Jsoup.connect("http://www.polyvore.com/bags/shop?category_id=35").get();
如果你这样做 System.out.println(doc.html());
,它 returns 整块 HTML 源代码,这与我们通过 Mozilla 和 Chrome 等浏览器看到的完全不同。
要解决此问题,您需要在 Jsoup 连接中指定 userAgent
参数,如下所示。
Document doc = null;
Elements aEles = null;
try {
// doc = Jsoup.connect("http://www.polyvore.com/bags/shop?category_id=35").get();
doc = Jsoup.connect("http://www.polyvore.com/bags/shop?category_id=35")
.userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
.referrer("http://www.google.com").get();
if (doc != null) {
aEles = doc.select("div.title > a");
if (aEles != null)
System.out.println("size: " + aEles.size());
}
} catch (Exception e) {
e.printStackTrace();
}
我有一个 html 文件,其中包含如下内容:
<div class="title"><a href="../dorothy_perkins_true_blue_suedette/thing?id=130434603" title="Dorothy Perkins True blue suedette clutch bag">Dorothy Perkins True blue suedette clutch bag</a></div>
我想提取 href
中的 url。我有以下代码:
Document doc = Jsoup.connect(url).get();
Elements products = doc.select("div.title a[href]");
System.out.println("size: "+products.size());
打印显示,但是,大小为 0。找不到任何匹配项。我使用的 url 是 http://www.polyvore.com/bags/shop?category_id=35
。你可以看看源代码,我很确定上面的代码是正确的。如果有人可以提供一些想法,那就太好了。非常感谢。
我相信你使用下面的代码来连接。
doc = Jsoup.connect("http://www.polyvore.com/bags/shop?category_id=35").get();
如果你这样做 System.out.println(doc.html());
,它 returns 整块 HTML 源代码,这与我们通过 Mozilla 和 Chrome 等浏览器看到的完全不同。
要解决此问题,您需要在 Jsoup 连接中指定 userAgent
参数,如下所示。
Document doc = null;
Elements aEles = null;
try {
// doc = Jsoup.connect("http://www.polyvore.com/bags/shop?category_id=35").get();
doc = Jsoup.connect("http://www.polyvore.com/bags/shop?category_id=35")
.userAgent("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
.referrer("http://www.google.com").get();
if (doc != null) {
aEles = doc.select("div.title > a");
if (aEles != null)
System.out.println("size: " + aEles.size());
}
} catch (Exception e) {
e.printStackTrace();
}