我想匹配以下 url 中的类别:news 和 politics
请注意,可能有 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 等的
>>> 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']
