java - 使用 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>
任何人都可以帮忙吗?谢谢你。
解决方案
您可以为此使用 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);
仅此而已,如果您还有其他需要,请随时提出!希望这对您有所帮助!
推荐阅读
- c++ - BST 节点删除 - 指针未正确删除?
- javascript - 如何在循环中使用图像加载?
- javascript - 如何通过 jQuery 动态重写 twitter 图片?
- android - 适用于 Android 的 Google 登录:无法解析 RC_SIGN_IN
- lstm - LSTM 单元和单元
- python - 在 Odoo 10 中编辑视图后无法访问数据库:内部服务器错误
- java - 未知 URL:content://media/external/audio/media/null?
- javascript - 使用 Javascript,如何检查用户的输入是否满足所有条件,然后显示输出?
- apache-kafka - 卡夫卡多消费者
- centos7 - Centoswebpanel roundcube 500 内部服务器错误