从URL获取域名?

mar*_*ith 33 c# uri

我试图从URL字符串中提取域名.我几乎拥有它......我正在使用URI

我有一个字符串..我的第一个想法是使用正则表达式,但后来我决定使用URI类

http://www.google.com/url?sa=t&source=web&ct=res&cd=1&ved=0CAgQFjAA&url=http://www.test.com/&rct=j&q=test&ei=G2phS-HdJJWTjAfckvHJDA&usg=AFQjCNFSEAztaqtkaIvEzxmRm2uOARn1kQ

我需要将上面的内容转换为google.com和google而不使用www

我做了以下

Uri test = new Uri(referrer);
log.Info("Domain part : " + test.Host);
Run Code Online (Sandbox Code Playgroud)

基本上这会返回www.google.com ....如果可能的话,我想尝试返回2个表单......如上所述...

google.com和谷歌

这有可能与URI?

Dew*_*wfy 28

是的,有可能使用:

Uri.GetLeftPart( UriPartial.Authority )
Run Code Online (Sandbox Code Playgroud)

  • 我实际上得到它返回相同没有http://但它有www ...使用Uri.Host (7认同)
  • 答案没有返回OP所要求的内容。不知道为什么它有这么多的赞成票。 (5认同)
  • 你读过这个问题吗?这将返回 httр://www.google.com (2认同)

ser*_*ail 17

@Dewfy:缺点是你的方法为"www.test.co.uk"返回"uk",但这里的域名显然是"test.co.uk".

@naivists:缺点是你的方法返回"beta.microsoft.com"为"www.beta.microsoft.com",但这里的域显然是"microsoft.com"

我需要相同的,所以我写了一个类,你可以复制并粘贴到你的解决方案中.它使用tld的硬编码字符串数组.http://pastebin.com/raw.php?i=VY3DCNhp

Console.WriteLine(GetDomain.GetDomainFromUrl("http://www.beta.microsoft.com/path/page.htm"));
Run Code Online (Sandbox Code Playgroud)

输出 microsoft.com

Console.WriteLine(GetDomain.GetDomainFromUrl("http://www.beta.microsoft.co.uk/path/page.htm"));
Run Code Online (Sandbox Code Playgroud)

输出 microsoft.co.uk

  • 当数百个新gTLD在今年晚些时候和明年推出时,这将不再有效......除非有人手动添加它们. (8认同)

Too*_*kit 9

使用 Nager.PublicSuffix

安装包 Nager.PublicSuffix

var domainParser = new DomainParser(new WebTldRuleProvider());

var domainName = domainParser.Get("sub.test.co.uk");
//domainName.Domain = "test";
//domainName.Hostname = "sub.test.co.uk";
//domainName.RegistrableDomain = "test.co.uk";
//domainName.SubDomain = "sub";
//domainName.TLD = "co.uk";
Run Code Online (Sandbox Code Playgroud)


nai*_*sts 6

google.com不保证与www.google.com相同(嗯,从这个例子来看,它在技术上是,但可能是其他方式).

也许您需要的是实际删除"顶级"域和"www"子域?然后只是split('.')在最后一部分之前采取部分!


小智 5

以下是一些仅提供SLD加gTLD或ccTLD扩展的代码(请注意下面的例外情况).我不关心DNS.

理论如下:

  • 3个令牌下的任何内容保持不变,例如"localhost","domain.com",否则:最后一个令牌必须是gTLD或ccTLD扩展.
  • 倒数第二个令牌被认为是扩展的一部分,如果它的长度<3,则包含在例外列表中.
  • 最后,在那之前的令牌被认为是SLD.之前的任何内容都被视为子域或主机限定符,例如Www.

至于代码,短而甜:

private static string GetDomainName(string url)
{
    string domain = new Uri(url).DnsSafeHost.ToLower();
    var tokens = domain.Split('.');
    if (tokens.Length > 2)
    {
        //Add only second level exceptions to the < 3 rule here
        string[] exceptions = { "info", "firm", "name", "com", "biz", "gen", "ltd", "web", "net", "pro", "org" }; 
        var validTokens = 2 + ((tokens[tokens.Length - 2].Length < 3 || exceptions.Contains(tokens[tokens.Length - 2])) ? 1 : 0);
        domain = string.Join(".", tokens, tokens.Length - validTokens, validTokens);
    }
    return domain;
}
Run Code Online (Sandbox Code Playgroud)

显而易见的例外是,这不会涉及双字母域名.因此,如果您足够幸运拥有ab.com,则需要稍微调整代码.对于我们来说,这个代码将涵盖几乎每个gTLD和ccTLD,减去一些非常奇特的代码.


Ced*_*i P 5

我几乎尝试了所有方法,但所有方法都达不到预期的效果.所以这是我从servermanfail调整的方法.

tld文件可以在https://publicsuffix.org/list/上获得. 我从https://publicsuffix.org/list/effective_tld_names.dat获取文件解析它并搜索tld的文件.如果发布了新的tld,只需下载最新的文件即可.

玩得开心.

using System;
using System.Collections.Generic;
using System.IO;

namespace SearchWebsite
{
internal class NetDomain
{
    static public string GetDomainFromUrl(string Url)
    {
        return GetDomainFromUrl(new Uri(Url));
    }

    static public string GetDomainFromUrl(string Url, bool Strict)
    {
        return GetDomainFromUrl(new Uri(Url), Strict);
    }

    static public string GetDomainFromUrl(Uri Url)
    {
        return GetDomainFromUrl(Url, false);
    }

    static public string GetDomainFromUrl(Uri Url, bool Strict)
    {
        initializeTLD();
        if (Url == null) return null;
        var dotBits = Url.Host.Split('.');
        if (dotBits.Length == 1) return Url.Host; //eg http://localhost/blah.php = "localhost"
        if (dotBits.Length == 2) return Url.Host; //eg http://blah.co/blah.php = "localhost"
        string bestMatch = "";
        foreach (var tld in DOMAINS)
        {
            if (Url.Host.EndsWith(tld, StringComparison.InvariantCultureIgnoreCase))
            {
                if (tld.Length > bestMatch.Length) bestMatch = tld;
            }
        }
        if (string.IsNullOrEmpty(bestMatch))
            return Url.Host; //eg http://domain.com/blah = "domain.com"

        //add the domain name onto tld
        string[] bestBits = bestMatch.Split('.');
        string[] inputBits = Url.Host.Split('.');
        int getLastBits = bestBits.Length + 1;
        bestMatch = "";
        for (int c = inputBits.Length - getLastBits; c < inputBits.Length; c++)
        {
            if (bestMatch.Length > 0) bestMatch += ".";
            bestMatch += inputBits[c];
        }
        return bestMatch;
    }


    static private void initializeTLD()
    {
        if (DOMAINS.Count > 0) return;

        string line;
        StreamReader reader = File.OpenText("effective_tld_names.dat");
        while ((line = reader.ReadLine()) != null)
        {
            if (!string.IsNullOrEmpty(line) && !line.StartsWith("//"))
            {
                DOMAINS.Add(line);
            }
        }
        reader.Close();
    }


    // This file was taken from https://publicsuffix.org/list/effective_tld_names.dat

    static public List<String> DOMAINS = new List<String>();
}
Run Code Online (Sandbox Code Playgroud)

}

  • 我已经使用了你的解决方案,它工作得很好,直到我发现了一些错误.例如,`www.navistar.com`没有删除`www`部分.这是修复`if(!url.Host.EndsWith("."+ tld,StringComparison.InvariantCultureIgnoreCase))继续;` (3认同)