使用 Python 切片 URL [英] Slicing URL with Python

查看:38
本文介绍了使用 Python 切片 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理大量 URL 列表.只是一个简单的问题,我试图将 URL 的一部分切掉,见下文:

http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3

我怎么能切掉:

http://www.domainname.com/page?CONTENT_ITEM_ID=1234

有时CONTENT_ITEM_ID后面有两个以上的参数,每次的ID都不一样,我想可以通过找到第一个&然后在此之前切掉字符 &,不太确定如何执行此操作.

干杯

解决方案

使用 urlparse 模块.检查这个功能:

导入urlparsedef process_url(url, keep_params=('CONTENT_ITEM_ID=',)):解析 = urlparse.urlsplit(url)Filtered_query='&'.join(qry_item对于 parsed.query.split('&') 中的 qry_item如果 qry_item.startswith(keep_params))返回 urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])

在您的示例中:

<预><代码>>>>process_url(a)'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'

这个函数有一个额外的好处,如果您决定还需要更多的查询参数,或者如果参数的顺序不固定,它会更容易使用,如下所示:

<预><代码>>>>url='http://www.domainname.com/page?other_value=xx&param3&CONTENT_ITEM_ID=1234&param1'>>>process_url(url, ('CONTENT_ITEM_ID', 'other_value'))'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234'

I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:

http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3

How could I slice out:

http://www.domainname.com/page?CONTENT_ITEM_ID=1234

Sometimes there is more than two parameters after the CONTENT_ITEM_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho.

Cheers

解决方案

Use the urlparse module. Check this function:

import urlparse

def process_url(url, keep_params=('CONTENT_ITEM_ID=',)):
    parsed= urlparse.urlsplit(url)
    filtered_query= '&'.join(
        qry_item
        for qry_item in parsed.query.split('&')
        if qry_item.startswith(keep_params))
    return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])

In your example:

>>> process_url(a)
'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'

This function has the added bonus that it's easier to use if you decide that you also want some more query parameters, or if the order of the parameters is not fixed, as in:

>>> url='http://www.domainname.com/page?other_value=xx&param3&CONTENT_ITEM_ID=1234&param1'
>>> process_url(url, ('CONTENT_ITEM_ID', 'other_value'))
'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234'

这篇关于使用 Python 切片 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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