【问题标题】:Find http:// and or www. and strip from domain. leaving domain.com找到 http:// 和或 www。并从域中剥离。离开 domain.com
【发布时间】:2013-01-15 13:10:42
【问题描述】:

我对 python 很陌生。我正在尝试解析 URL 文件以仅保留域名。

我的日志文件中的一些 url 以 http:// 开头,一些以 www 开头。一些以两者开头。

这是我的代码中去掉 http:// 部分的部分。我需要添加什么来查找 http 和 www。并删除两者?

line = re.findall(r'(https?://\S+)', line)

目前,当我运行代码时,只有 http:// 被剥离。如果我将代码更改为以下内容:

line = re.findall(r'(https?://www.\S+)', line)

只有以两者开头的域会受到影响。 我需要代码更有条件。 TIA

编辑...这是我的完整代码...

import re
import sys
from urlparse import urlparse

f = open(sys.argv[1], "r")

for line in f.readlines():
 line = re.findall(r'(https?://\S+)', line)
 if line:
  parsed=urlparse(line[0])
  print parsed.hostname
f.close()

我被原始帖子误认为是正则表达式。它确实在使用 urlparse。

【问题讨论】:

标签: python url urlparse


【解决方案1】:

你可以在这里不用正则表达式。

with open("file_path","r") as f:
    lines = f.read()
    lines = lines.replace("http://","")
    lines = lines.replace("www.", "") # May replace some false positives ('www.com')
    urls = [url.split('/')[0] for url in lines.split()]
    print '\n'.join(urls)

示例文件输入:

http://foo.com/index.html
http://www.foobar.com
www.bar.com/?q=res
www.foobar.com

输出:

foo.com
foobar.com
bar.com
foobar.com

编辑:

可能会有一个棘手的 url,比如 foobarwww.com,上面的方法会去掉 www。然后我们将不得不恢复使用正则表达式。

lines = lines.replace("www.", "") 行替换为lines = re.sub(r'(www.)(?!com)',r'',lines)。当然,所有可能的 TLD 都应该用于不匹配模式。

【讨论】:

  • @DSM 别担心,它没有被使用;)
  • 谢谢,这行得通 :) 知道如何删除 .co.uk/.com 等之后的所有内容吗?
  • 我没明白你的意思。能举例说明吗?
  • 当然。一些 url 是指向页面的链接。所以在 foo.com/index.htm 的情况下,我想只留下 foo.com
  • 太棒了,按我的意愿工作。非常感谢。很抱歉很痛苦,我发现 python 的文档很难理解。您能否解释一下您对代码所做的一些修改,以便让我了解它是如何工作的?再次感谢。
【解决方案2】:

查看urlparse library,它可以自动为您完成这些事情。

>>> urlparse.urlsplit('http://www.google.com.au/q?test')
SplitResult(scheme='http', netloc='www.google.com.au', path='/q', query='test', fragment='')

【讨论】:

    【解决方案3】:

    对于这种特定情况可能有点矫枉过正,但我​​通常会使用 urlparse.urlsplit (Python 2) 或 urllib.parse.urlsplit (Python 3)。

    from urllib.parse import urlsplit  # Python 3
    from urlparse import urlsplit  # Python 2
    import re
    
    url = 'www.python.org'
    
    # URLs must have a scheme
    # www.python.org is an invalid URL
    # http://www.python.org is valid
    
    if not re.match(r'http(s?)\:', url):
        url = 'http://' + url
    
    # url is now 'http://www.python.org'
    
    parsed = urlsplit(url)
    
    # parsed.scheme is 'http'
    # parsed.netloc is 'www.python.org'
    # parsed.path is None, since (strictly speaking) the path was not defined
    
    host = parsed.netloc  # www.python.org
    
    # Removing www.
    # This is a bad idea, because www.python.org could 
    # resolve to something different than python.org
    
    if host.startswith('www.'):
        host = host[4:]
    

    【讨论】:

    • 不适用于以“http://”开头的 URL。 urlparse.urlsplit("www.foo.com").netloc 将返回 ''
    • 是的,那是因为www.foo.com 不是有效的网址。
    • 问题是OP的文件中的一些url是这种格式的。
    • 尝试以这种方式改变SplitResult.netloc 将导致AttributeError 被提升。为了更改netloc,您需要使用_replace,就像replaced = parsed._replace(netloc=host[4:])
    • 我不会改变netloc。我是吗?
    【解决方案4】:

    您可以使用urlparse。此外,解决方案应该是通用的,以删除域名前的“www”以外的内容(即处理 server1.domain.com 之类的情况)。以下是应该可行的快速尝试:

    from urlparse import urlparse
    
    url = 'http://www.muneeb.org/files/alan_turing_thesis.jpg'
    
    o = urlparse(url)
    
    domain = o.hostname
    
    temp = domain.rsplit('.')
    
    if(len(temp) == 3):
        domain = temp[1] + '.' + temp[2]
    
    print domain 
    

    【讨论】:

      【解决方案5】:

      我遇到了同样的问题。这是一个基于正则表达式的解决方案:

      >>> import re
      >>> rec = re.compile(r"https?://(www\.)?")
      
      >>> rec.sub('', 'https://domain.com/bla/').strip().strip('/')
      'domain.com/bla'
      
      >>> rec.sub('', 'https://domain.com/bla/    ').strip().strip('/')
      'domain.com/bla'
      
      >>> rec.sub('', 'http://domain.com/bla/    ').strip().strip('/')
      'domain.com/bla'
      
      >>> rec.sub('', 'http://www.domain.com/bla/    ').strip().strip('/')
      'domain.com/bla'
      

      【讨论】:

        【解决方案6】:

        我相信@Muneeb Ali 是最接近解决方案的,但问题出现在诸如 frontdomain.domain.co.uk....之类的时候。

        我想:

        for i in range(1,len(temp)-1):
            domain = temp[i]+"."
        domain = domain + "." + temp[-1]
        

        有更好的方法吗?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-03
          • 1970-01-01
          • 2016-02-14
          • 2010-09-10
          • 2010-09-26
          • 2012-11-07
          • 2012-08-07
          相关资源
          最近更新 更多