-2

基于上一个问题Parsing URI parameter and keyword value pairs的后续内容,我想对具有相同域和页面名称的 URL 进行分组,然后是所有参数和值。URL 可以具有相同或不同数量的参数和/或相应的值。将打印 URL/页面值,然后是它的所有参数和关键字值。

我正在寻找使用 Python 解析、分组和打印值的答案。我无法通过 Google 或 SO 找到答案。

具有各种参数和值的 URL 示例源:

www.domain.com/page?id_eve=479989&adm=no
www.domain.com/page?id_eve=47&adm=yes
www.domain.com/page?id_eve=479
domain.com/cal?view=month
domain.com/cal?view=day
ww2.domain.com/cal?date=2007-04-14
ww2.domain.com/cal?date=2007-08-19
www.domain.edu/some/folder/image.php?l=adm&y=5&id=2&page=http%3A//support.domain.com/downloads/index.asp&unique=12345
blog.news.org/news/calendar.php?view=day&date=2011-12-10
www.domain.edu/some/folder/image.php?l=adm&y=5&id=2&page=http%3A//.domain.com/downloads/index.asp&unique=12345
blog.news.org/news/calendar.php?view=month&date=2011-12-10

我正在寻找的示例输出。URL 和来自所有相同 URL 的参数/值组合列表是原始的。

www.domain.com/page
id_eve=479989
id_eve=47
id_eve=479
adm=no
adm=yes
domain.com/cal
view=month
view=day
w2.domain.com/cal
date=2007-04-14
date=2007-08-19
www.domain.edu/some/folder/image.php
l=adm
l-adm
id=2
id=2
page=http%3A//.domain.com/downloads/index.asp
page=http%3A//support.domain.com/downloads/index.asp
4

1 回答 1

2

用于defaultdict()收集每个 url 路径的参数:

from collections import defaultdict
from urllib import quote
from urlparse import parse_qsl, urlparse


urls = defaultdict(list)
with open('links.txt') as f:
    for url in f:
        parsed_url = urlparse(url.strip())
        params = parse_qsl(parsed_url.query, keep_blank_values=True)
        for key, value in params:
            urls[parsed_url.path].append("%s=%s" % (key, quote(value)))

# printing results
for url, params in urls.iteritems():
    print url
    for param in params:
        print param

印刷:

ww2.domain.com/cal
date=2007-04-14
date=2007-08-19
www.domain.edu/some/folder/image.php
l=adm
y=5
id=2
page=http%3A//support.domain.com/downloads/index.asp
unique=12345
l=adm
y=5
id=2
page=http%3A//.domain.com/downloads/index.asp
unique=12345
domain.com/cal
view=month
view=day
www.domain.com/page
id_eve=479989
adm=no
id_eve=47
adm=yes
id_eve=479
blog.news.org/news/calendar.php
view=day
date=2011-12-10
view=month
date=2011-12-10

希望有帮助。

于 2013-09-18T19:51:42.930 回答