首页 > 解决方案 > 使用 Jsoup 抓取网页

问题描述

我需要使用 Jsoup 从下面的 HTML 中抓取邮政编码。我只需要作为标签href属性一部分的邮政编码。a在此示例中,邮政编码部分是W2

<a href="/properties-for-sale/w2/chpk3848653" class="property_photo_holder" style="backgroundimage:url(https://assets.foxtons.co.uk/w/480/1523289105/chpk3848653-23.jpg)"></a>

这是 HTML:

</div>

<div id="property_1062067" class="property_summary">

<h6><a href="/properties-for-sale/w2/chpk3848653">Lancaster Gate, <span class="property_address_location_name">Bayswater,</span> W2</a></h6>

任何人都可以帮忙吗?谢谢你。

标签: javahtmlparsingweb-scrapingjsoup

解决方案


您可以为此使用 JSOUP,您只需要检索 href 属性值,如下所示:

Document document = Jsoup.connect(URL).userAgent("Mozilla/5.0").get();

Elements elements = document.select("a");

String href = elements.attr("href");

现在您将 href 属性作为字符串,您需要应用 RegEx(正则表达式)来获取所需的字段,在这种情况下,邮政编码包含在:“/properties-for-sale/w2/chpk3848653”中. 为此,您需要:

String regex = "[a-zA-Z0-9]{11}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(href);

String postalCode = matcher.find().group(0);

仅此而已,如果您还有其他需要,请随时提出!希望这对您有所帮助!


推荐阅读