如何拆分网址 [英] How to split a web address

查看:46
本文介绍了如何拆分网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

<预><代码>>>>从 urlparse 导入 urlparse>>>>>>部分 = urlparse("http://www.stackoverflow.com/questions/ask")>>>part.scheme + "://" + parts.netloc'http://www.stackoverflow.com'>>>零件路径'/问题/问'

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

So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address http://www.stackoverflow.com/questions/ask. I would need the protocol and domain (e.g. http://www.stackoverflow.com) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?

解决方案

Dan is right: urlparse is your friend:

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

Note: In Python 3 it's from urllib.parse import urlparse

这篇关于如何拆分网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆