Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—将url拆分为其组件_Python_Regex_Urlparse - Fatal编程技术网

Python—将url拆分为其组件

Python—将url拆分为其组件,python,regex,urlparse,Python,Regex,Urlparse,我有一个巨大的URL列表,都是这样的: http://www.example.com/site/section1/VAR1/VAR2 ParseResult(scheme='http', netloc='www.example.com', path='/site/section1/VAR1/VAR2', params='', query='', fragment='') 其中VAR1和VAR2是url的动态元素。我想做的是从这个url字符串中只提取VAR1。我已尝试使用,但输出如下所示: h

我有一个巨大的URL列表,都是这样的:

http://www.example.com/site/section1/VAR1/VAR2
ParseResult(scheme='http', netloc='www.example.com', path='/site/section1/VAR1/VAR2', params='', query='', fragment='')
其中VAR1和VAR2是url的动态元素。我想做的是从这个url字符串中只提取VAR1。我已尝试使用,但输出如下所示:

http://www.example.com/site/section1/VAR1/VAR2
ParseResult(scheme='http', netloc='www.example.com', path='/site/section1/VAR1/VAR2', params='', query='', fragment='')

或者,您可以应用
split()
方法:

>>> url = "http://www.example.com/site/section1/VAR1/VAR2"
>>> url.split("/")[-2:]
['VAR1', 'VAR2']

你可以大致记住这一点。可以使用
urlparse
获得url的不同部分。在这里,您可以通过
urlparse(url.path
获得
path
,然后通过
split()
函数获得所需的变量

>>> from urlparse import urlparse
>>> url = 'http://www.example.com/site/section1/VAR1/VAR2' 
>>> urlparse(url)
ParseResult(scheme='http', netloc='www.example.com', path='/site/section1/VAR1/VAR2', params='', query='', fragment='')
>>> urlparse(url).path
'/site/section1/VAR1/VAR2'
>>> urlparse(url).path.split('/')[-2]
'VAR1'
我只想试试

url = 'http://www.example.com/site/section1/VAR1/VAR2'
var1 = url.split('/')[-2]

检查这一个,它是相当有效的,因为它从字符串的末尾开始,使用maxsplit选项,我们可以停止拆分的数量

最后,您可以使用索引来获取url的最后两部分

>>> url.rsplit('/',2)[1:]
['VAR1', 'VAR2']

rsplit比split更有效,因为它使用maxslit参数保存拆分。对于python 3,它来自urllib.parse import urlparse