1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import re
- import sys
- from pathlib import Path
- from urllib import request
- RE_HREF = re.compile(b'.*href="([^"]+)".*')
- RE_LINK = re.compile(b'(<link[^>]+rel="canonical"[^>]+)')
- def main(url: str) -> int:
- print('downloading...', file=sys.stderr)
- with request.urlopen(url) as response:
- print('parsing...', file=sys.stderr)
- try:
- if link_match := next(RE_LINK.finditer(response.read())):
- if link := link_match.group(1):
- if href_match := RE_HREF.match(link):
- print(Path(href_match.group(1).decode()).name)
- return 0
- except StopIteration:
- pass
- print('failed to extract id', file=sys.stderr)
- return 1
- if __name__ == '__main__':
- if len(sys.argv) != 2 or sys.argv[1] in ('-h', '--help'):
- print(
- 'usage: python3 %s url\n' % sys.argv[0],
- 'get channel id from channel url',
- 'for example:',
- ' * https://www.youtube.com/c/ChannelName',
- ' * https://www.youtube.com/user/UserName',
- sep='\n', file=sys.stderr
- )
- else:
- sys.exit(main(sys.argv[1]))
|