找到http://和/或www。并从域中剥离。离开domain.com

时间:2013-01-31 12:22:08

标签: python url urlparse

我对python很新。我正在尝试解析一个URL文件,只留下域名。

我的日志文件中的一些网址以http://开头,有些网址以www.Some开头,以两者开头。

这是我的代码中删除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。

6 个答案:

答案 0 :(得分:18)

对于这种特定情况可能有点过分,但我通常使用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:]

答案 1 :(得分:7)

你可以在这里没有正则表达式。

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

修改

可能有一个像foobarwww.com这样棘手的网址,而上述方法会删除www。我们将不得不恢复使用正则表达式。

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

答案 2 :(得分: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'

答案 3 :(得分:4)

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

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

答案 4 :(得分:1)

您可以使用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 :(得分:0)

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

我想:

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

有更好的方法吗?