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

Pau*_*ank 12 python url urlparse

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

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

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

line = re.findall(r'(https?://\S+)', line)
Run Code Online (Sandbox Code Playgroud)

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

line = re.findall(r'(https?://www.\S+)', line)
Run Code Online (Sandbox Code Playgroud)

只有以两者开头的域都会受到影响.我需要代码更有条件.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()
Run Code Online (Sandbox Code Playgroud)

我把原帖误认为正则表达式.它确实使用urlparse.

Mar*_*zer 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:]
Run Code Online (Sandbox Code Playgroud)


sid*_*idi 8

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

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)
Run Code Online (Sandbox Code Playgroud)

示例文件输入:

http://foo.com/index.html
http://www.foobar.com
www.bar.com/?q=res
www.foobar.com
Run Code Online (Sandbox Code Playgroud)

输出:

foo.com
foobar.com
bar.com
foobar.com
Run Code Online (Sandbox Code Playgroud)

编辑:

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

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


the*_*het 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'
Run Code Online (Sandbox Code Playgroud)