使用JSoup爬取电子邮件和链接

4

我希望使用JSoup来提取一个网站的所有电子邮件地址和URL,并将其存储在哈希集中(这样就不会重复)。我正在尝试做到这一点,但我不确定我需要在选择器中放入什么,或者我是否做得正确。以下是代码:

Document doc = Jsoup.connect(link).get();

Elements URLS = doc.select("");
Elements emails = doc.select("");
emailSet.add(emails.toString());
linksToVisit.add(URLS.toString());
2个回答

6

请按照以下步骤操作:


获取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"));
}

这里有完整可用的代码,与IT技术有关: https://gist.github.com/JonasCz/a3b81def26ecc047ceb5请勿滥发垃圾信息!

2

这是我的工作解决方案,它将不仅在文本中搜索电子邮件,还会在代码中进行搜索:

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接