Skip to main content
 首页 » 编程设计

python之使用正则表达式查找不包含某些信息的 URL

2025年02月15日43oomusou

我正在使用 Python 3.5 和 re 模块开发一个抓取器/网络爬虫,其中一个功能需要检索 YouTube channel 的 URL。我正在使用包含正则表达式匹配的以下代码部分来完成此操作:

href = re.compile("(/user/|/channel/)(.+)") 

它应该返回类似/user/username 或/channel/channelname 的内容。它在大多数情况下都成功地做到了这一点,但有时它会抓取一种包含更多信息的 URL,例如 /user/username/videos?view=60 或在用户名/ 部分。

为了解决这个问题,我将上面的代码重写为

href = re.compile("(/user/|/channel/)(?!(videos?view=60)(.+)") 

以及其他变体都没有成功。我如何重写我的代码,以便它获取在 URL 中任何位置不包含 videos?view=60 的 URLS?

请您参考如下方法:

将以下方法与特定的正则表达式模式结合使用:

user_url = '/user/username/videos?view=60' 
channel_url = '/channel/channelname/videos?view=60' 
 
pattern = re.compile(r'(/user/|/channel/)([^/]+)') 
 
m = re.match(pattern, user_url) 
print(m.group())    # /user/username 
 
m = re.match(pattern, channel_url) 
print(m.group())    # /channel/channelname