我想匹配以下网址中的类别:newspolitics

请注意,可能有1个或多个类别。可以通过在文本或数字的两边加上/来标识类别。

我试过的

item.url = 'http://www.example.com/news/politics/this-is-article-name-1993591'

compiled_regex = re.compile('/.+(?!/)/')

match = compiled_regex.search(item.url)


回应为/

我想要的(预期结果):

match.group(0) = `news`
match.group(1) = `politics`

最佳答案

我会使用urllib.parse而不是正则表达式来解析网址等

>>> url = 'http://www.example.com/news/politics/this-is-article-name-1993591'
>>> import urllib.parse

>>> urllib.parse.urlparse(url)
ParseResult(scheme='http',
            netloc='www.example.com',
            path='/news/politics/this-is-article-name-1993591',
            params='',
            query='',
            fragment='')

>>> urllib.parse.urlparse(url).path
'/news/politics/this-is-article-name-1993591'

>>> urllib.parse.urlparse(url).path.split('/')[1:-1]
['news', 'politics']

09-07 17:17
查看更多