我想使用JSoup来提取网站的所有电子邮件地址和网址,并将其存储在一个哈希集中(因此不会重复)。我试图这样做,但我不确定我需要在选择中输入什么,或者我是否正确行事。这是代码:
Document doc = Jsoup.connect(link).get();
Elements URLS = doc.select("");
Elements emails = doc.select("");
emailSet.add(emails.toString());
linksToVisit.add(URLS.toString());
答案 0 :(得分:7)
这样做:
获取html文档:
Document doc = Jsoup.connect(link).get();
使用正则表达式将电子邮件提取到HashSet中,以提取页面上的所有电子邮件地址:
Pattern p = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+");
Matcher matcher = p.matcher(doc.text());
Set<String> emails = new HashSet<String>();
while (matcher.find()) {
emails.add(matcher.group());
}
提取链接:
Set<String> links = new HashSet<String>();
Elements elements = doc.select("a[href]");
for (Element e : elements) {
links.add(e.attr("href"));
}
此处完整且有效的代码:add_custom_command
现在不要成为垃圾邮件发送者!
答案 1 :(得分:1)
这是我的工作解决方案,它不仅可以在文本中搜索电子邮件,还可以在代码中搜索电子邮件:
public Set<String> getEmailsByUrl(String url) {
Document doc;
Set<String> emailSet = new HashSet<>();
try {
doc = Jsoup.connect(url)
.userAgent("Mozilla")
.get();
Pattern p = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+");
Matcher matcher = p.matcher(doc.body().html());
while (matcher.find()) {
emailSet.add(matcher.group());
}
} catch (IOException e) {
e.printStackTrace();
}
return emailSet;
}