【问题标题】:using JSoup to scrape emails and links使用 JSoup 抓取电子邮件和链接
【发布时间】:2015-05-28 01:22:04
【问题描述】:

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

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

Elements URLS = doc.select("");
Elements emails = doc.select("");
emailSet.add(emails.toString());
linksToVisit.add(URLS.toString());

【问题讨论】:

    标签: web-scraping set jsoup


    【解决方案1】:

    这样做:


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

    完整且有效的代码在这里: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;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-08-09
        • 2019-03-11
        • 2022-06-16
        • 1970-01-01
        • 2012-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多