2
2
import logging
3
3
import re
4
4
import urllib .request
5
+ import aiohttp
6
+
7
+ headers = {
8
+ 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.24 Safari/537.36' }
5
9
6
10
7
11
async def getLiveVideoId (id ):
@@ -15,26 +19,30 @@ async def getLiveVideoId(id):
15
19
16
20
17
21
async def checkIsLive (videoid ):
18
- fp = urllib .request .urlopen (urllib .request .Request (
19
- f"https://www.youtube.com/watch?v={ videoid } " , headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.24 Safari/537.36' }))
20
- mybytes = fp .read ()
21
- fp .close ()
22
- htmlsource = mybytes .decode ("utf-8" )
23
- if re .search (r'"isLive\\":true,' , htmlsource ) is None : # \"isLive\":true,
24
- return None
25
- return id
22
+ async with aiohttp .ClientSession () as session :
23
+ async with session .get (f"https://www.youtube.com/watch?v={ videoid } " , headers = headers ) as r :
24
+ if r .status == 200 :
25
+ htmlsource = await r .text ()
26
+ if re .search (r'"isLive\\":true,' , htmlsource ) is None : # \"isLive\":true,
27
+ return None
28
+ return id
29
+ else :
30
+ logging .error ('checkIsLive.status:' + r .status )
31
+ return None
26
32
27
33
28
34
async def channelId2videoId (channelId ):
29
- fp = urllib .request .urlopen (urllib .request .Request (
30
- f"https://www.youtube.com/channel/{ channelId } /live" , headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.24 Safari/537.36' }))
31
- mybytes = fp .read ()
32
- fp .close ()
33
- htmlsource = mybytes .decode ("utf-8" )
34
- if re .search (r'"isLive\\":true,' , htmlsource ) is None : # \"isLive\":true,
35
- return None
36
- videoid = re .search (r'(?<="videoId\\":\\")(.*?)(?=\\",)' , htmlsource )
37
- if re .search (r'(?<="videoId\\":\\")(.*?)(?=\\",)' , htmlsource ) is None :
38
- logging .warn (r're.search[videoId], htmlsource) is None' )
39
- return None
40
- return videoid .group ()
35
+ async with aiohttp .ClientSession () as session :
36
+ async with session .get (f"https://www.youtube.com/channel/{ channelId } /live" , headers = headers ) as r :
37
+ if r .status == 200 :
38
+ htmlsource = await r .text ()
39
+ if re .search (r'"isLive\\":true,' , htmlsource ) is None : # \"isLive\":true,
40
+ return None
41
+ videoid = re .search (r'(?<="videoId\\":\\")(.*?)(?=\\",)' , htmlsource )
42
+ if re .search (r'(?<="videoId\\":\\")(.*?)(?=\\",)' , htmlsource ) is None :
43
+ logging .warn (r're.search[videoId], htmlsource) is None' )
44
+ return None
45
+ return videoid .group ()
46
+ else :
47
+ logging .error ('channelId2videoId.status:' + r .status )
48
+ return None
0 commit comments