【问题标题】:How to split a web address [duplicate]如何拆分网址[重复]
【发布时间】:2010-09-22 02:49:33
【问题描述】:

所以我正在使用 python 对网页进行一些解析,我想将完整的网址分成两部分。假设我有地址http://www.stackoverflow.com/questions/ask。我需要协议和域(例如http://www.stackoverflow.com)和路径(例如/questions/ask)。我认为这可以通过一些正则表达式来解决,但是我对此并不那么方便。有什么建议吗?

【问题讨论】:

标签: python string url split


【解决方案1】:
import re
url = "http://stackoverflow.com/questions/ask"
protocol, domain = re.match(r"(http://[^/]*)(.*)", url).groups()

【讨论】:

    【解决方案2】:

    使用 Python urlparse 模块:

    https://docs.python.org/library/urlparse.html

    对于像这样一个定义明确且广为流传的问题,不要费心编写自己的代码,更不用说自己的正则表达式了。它们会造成太多麻烦;-)。

    【讨论】:

      【解决方案3】:

      Dan 是对的:urlparse 是你的朋友:

      >>> from urlparse import urlparse
      >>>
      >>> parts = urlparse("http://www.stackoverflow.com/questions/ask")
      >>> parts.scheme + "://" + parts.netloc
      'http://www.stackoverflow.com'
      >>> parts.path
      '/questions/ask'
      

      注意:在 Python 3 中是from urllib.parse import urlparse

      【讨论】:

      • 一定会喜欢电池包含哲学。我一开始以为正则表达式 b/c 我不知道包含电池。谢谢。
      猜你喜欢
      • 2018-12-28
      • 2013-10-28
      • 1970-01-01
      • 2016-12-06
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      相关资源
      最近更新 更多