草庐IT

爬网网站提取电子邮件

程序员大本营 2024-06-04 原文

我有一个网络爬网,无法正常工作。如果我访问页面, http://www.canon.de/support/consumer_products/contact_support/ 然后,我想从此页面提取电子邮件。此外,如果有佳能的其他网站引用(这是),那么我的爬行者将访问所有这些页面以收集邮件。

不幸的是,我的方法“ searchforword”不起作用,我永远不会达到IF语句,我不知道为什么。我的错误在哪里?

这是我的课:

蜘蛛

 public class Spider { private static final int MAX_PAGES_TO_SEARCH = 10;    private Set<String> pagesVisited = new HashSet<String>();    private List<String> pagesToVisit = new LinkedList<String>();    /**     * Our main launching point for the Spider's functionality. Internally it creates spider legs     * that make an HTTP request and parse the response (the web page).     *      * @param url     *            - The starting point of the spider     * @param searchWord     *            - The word or string that you are searching for     */    public void search(String url)    {        while(this.pagesVisited.size() < MAX_PAGES_TO_SEARCH)        {            String currentUrl;            SpiderLeg leg = new SpiderLeg();            if(this.pagesToVisit.isEmpty())            {                currentUrl = url;                this.pagesVisited.add(url);            }            else            {                currentUrl = this.nextUrl();            }            leg.crawl(currentUrl); // Lots of stuff happening here. Look at the crawl method in                                   // SpiderLeg            leg.searchForWord(currentUrl);            this.pagesToVisit.addAll(leg.getLinks());        }        System.out.println("\n**Done** Visited " + this.pagesVisited.size() + " web page(s)");    }    /**     * Returns the next URL to visit (in the order that they were found). We also do a check to make     * sure this method doesn't return a URL that has already been visited.     *      * @return     */    private String nextUrl()    {        String nextUrl;        do        {            nextUrl = this.pagesToVisit.remove(0);        } while(this.pagesVisited.contains(nextUrl));        this.pagesVisited.add(nextUrl);        return nextUrl;    }  }  

蜘蛛侠

public class SpiderLeg{// We'll use a fake USER_AGENT so the web server thinks the robot is a  normal web browser.      private static final String USER_AGENT =        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML,       like Gecko) Chrome/13.0.782.112 Safari/535.1";private List<String> links = new LinkedList<String>();private Document htmlDocument;/** * This performs all the work. It makes an HTTP request, checks the response, and then gathers * up all the links on the page. Perform a searchForWord after the successful crawl *  * @param url *            - The URL to visit * @return whether or not the crawl was successful */public boolean crawl(String url){    try    {        Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);        Document htmlDocument = connection.get();        this.htmlDocument = htmlDocument;        if(connection.response().statusCode() == 200) // 200 is the HTTP OK status code                                                      // indicating that everything is great.        {           System.out.println("\n**Visiting** Received web page at " + url);        }        if(!connection.response().contentType().contains("text/html"))        {            System.out.println("**Failure** Retrieved something other than HTML");            return false;        }        Elements linksOnPage = htmlDocument.select("a[href]");        //System.out.println("Found (" + linksOnPage.size() + ") links");        for(Element link : linksOnPage)        {            this.links.add(link.absUrl("href"));        }        return true;    }    catch(IOException ioe)    {        // We were not successful in our HTTP request        return false;    }}public void searchForWord(String searchWord){    Pattern pattern =              Pattern.compile("([\\w\\-]([\\.\\w])+[\\w][email protected]([\\w\\-]+\\.)+[A-Za-z]{2,4})");              Matcher matchs = pattern.matcher(searchWord);              if (matchs.find()) {                      System.out.println(searchWord.substring( matchs.start(), matchs.end()));              }              else                  System.out.println("hdhdadsad");}public List<String> getLinks(){    return this.links;}}

蜘蛛网

public class SpiderTest{    public static void main(String[] args)    {        Spider spider = new Spider();        spider.search("http://www.canon.de/support/consumer_products/contact_support/");    }}

看答案

您的正则是有效的。

看这里 http://www.regexpal.com/?fam=97822

使用以下代码而不是 if 查找所有匹配:

while (matchs.find()) {    System.out.println(matchs.group());}

有关爬网网站提取电子邮件的更多相关文章

  1. ruby-on-rails - Rails - 从命名路由中提取 HTTP 动词 - 2

    Rails中有没有一种方法可以提取与路由关联的HTTP动词?例如,给定这样的路线:将“users”匹配到:“users#show”,通过:[:get,:post]我能实现这样的目标吗?users_path.respond_to?(:get)(显然#respond_to不是正确的方法)我最接近的是通过执行以下操作,但它似乎并不令人满意。Rails.application.routes.routes.named_routes["users"].constraints[:request_method]#=>/^GET$/对于上下文,我有一个设置cookie然后执行redirect_to:ba

  2. ruby-on-rails - Ruby - 如何从 ruby​​ 上的 .pfx 文件中提取公钥、rsa 私钥和 CA key - 2

    我有一个.pfx格式的证书,我需要使用ruby​​提取公共(public)、私有(private)和CA证书。使用shell我可以这样做:#ExtractPublicKey(askforpassword)opensslpkcs12-infile.pfx-outfile_public.pem-clcerts-nokeys#ExtractCertificateAuthorityKey(askforpassword)opensslpkcs12-infile.pfx-outfile_ca.pem-cacerts-nokeys#ExtractPrivateKey(askforpassword)o

  3. ruby - 如何在ruby中提取方括号内的内容 - 2

    我正在尝试提取方括号内的内容。到目前为止,我一直在使用它,它有效,但我想知道我是否可以直接在正则表达式中使用某些东西,而不是使用这个删除功能。a="Thisissuchagreatday[coolawesome]"a[/\[.*?\]/].delete('[]')#=>"coolawesome" 最佳答案 差不多。a="Thisissuchagreatday[coolawesome]"a[/\[(.*?)\]/,1]#=>"coolawesome"a[/(?"coolawesome"第一个依赖于提取组而不是完全匹配;第二个利用前瞻和

  4. ruby-on-rails - 验证电子邮件地址是 Paypal 用户 - 2

    我想验证一个电子邮件地址是否是PayPal用户。是否有API调用来执行此操作?是否有执行此操作的ruby​​库?谢谢 最佳答案 GetVerifiedStatus来自PayPal'sAdaptiveAccounts平台会为您做这件事。PayPal没有任何codesamples或SDKs用于Ruby中的自适应帐户,但我确实找到了编写codeforGetVerifiedStatusinRuby的人.您需要更改该代码以检查他们拥有的帐户类型的唯一更改是更改if@xml['accountStatus']!=nilaccount_status

  5. ruby-on-rails - Ruby on Rails - 需要在每周的特定时间将消息发送到电子邮件 - 2

    我想知道我应该如何着手这个项目。我需要每周向人们发送一次电子邮件。但是,这必须在每周的特定时间自动生成并发送。编码有多难?我需要知道是否有任何书籍可以提供帮助,或者你们中的任何人是否可以指导我。它必须使用ruby​​onrails进行编程。因此有一个网络服务和数据库集成。干杯 最佳答案 为什么这么复杂?您只需安排工作。您可以使用Delayed::Job例如。Delayed::Job让您可以使用run_at符号在特定时间安排作业,如下所示:Delayed::Job.enqueue(SendEmailJob.new(...),:run_

  6. 用于从 Open3.popen3 标准输出中提取值的正则表达式 - 2

    如何获取外部命令的输出并从中提取值?我有这样的东西:stdin,stdout,stderr,wait_thr=Open3.popen3("#{path}/foobar",configfile)if/exit0/=~wait_thr.value.to_srunlog.puts("Foobarexitednormally.\n")puts"Testcompleted."someoutputvalue=stdout.read("TX.*\s+(\d+)\s+")puts"Outputvalue:"+someoutputvalueend我没有在标准输出上使用正确的方法,因为Ruby告诉我它不能

  7. ruby - 使用 Ruby CSV 提取一列 - 2

    我一直在尝试从csv文件中获取单个列。我已经阅读了文档,http://www.ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html但仍然不太了解如何使用它。如果我使用CSV.table,与CSV.read相比,响应速度非常慢。我承认我正在加载的数据集非常大,这正是我只想从中获取单个列的原因。我的请求目前看起来像这样@dataTable=CSV.table('path_to_csv.csv')当我调试时,我得到了的响应#ThedocumentationsaysIshouldbeabletouseby_col(),butwhenItrytooutpu

  8. ruby - 在 Ruby 中,如何从具有值的哈希中提取键 - 2

    当我写这篇文章时,我以为我是Ruby巨人:#havingthishashhash={'Portugal'=>1,'France'=>2,'USA'=>3}#country_idcomesfrominputcountry_name=(hash.select{|k,v|v==country_id.to_i}.first||[]).first它确实正确地提取了国家名称,如果找不到国家也不会失败。我对此非常满意。但是我的导师说它可以/应该在可读性、长度和性能方面进行优化!还有什么比这更清晰/更快的呢?请指教 最佳答案 嗯,看来你的导师是对的

  9. ruby-on-rails - 在 Ruby 中提取 IMG 标签 - 2

    是否可以从Ruby中的HTMLblock中提取IMG标签(或只是IMG标签的src属性)?例如,如果我有一个HTMLblock,例如:Loremipsumdolorsitamet,laboreetdoloremagnaaliqua.Duisauteiruredolorinreprehenderitinvoluptatevelitessecillumdoloreeufugiatnullapariatur.我可以通过正则表达式或其他方法只提取IMG标签或该IMG标签的src吗?提前感谢您的任何建议! 最佳答案 使用Nokogiri:re

  10. ruby - 如何从 Proc 对象中提取代码? - 2

    给定一个Proc对象,是否可以查看其中的代码?例如:p=Proc.new{test=0}我需要的是通过某种方式从已创建的Proc对象中获取字符串“test=0”。 最佳答案 您可以使用ruby2ruby图书馆:>>#testedwith1.8.7>>require"parse_tree"=>true>>require"ruby2ruby"=>true>>require"parse_tree_extensions"=>true>>p=Proc.new{test=0}>>p.to_ruby=>"proc{test=0}"您还可以将此过程

随机推荐