Skip to content

Commit 1be11b1

Browse files
authored
Handle unavailable downloading url (#97)
1 parent 0c94535 commit 1be11b1

1 file changed

Lines changed: 23 additions & 18 deletions

File tree

baidupcs_py/baidupcs/pcs.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from pathlib import Path
66
from urllib.parse import urlparse, quote_plus
7+
from urllib.error import URLError, HTTPError
78
from base64 import standard_b64encode
89
import re
910
import json
@@ -986,25 +987,29 @@ def download_link(self, remotepath: str, pcs: bool = False) -> Optional[str]:
986987
headers = dict(PCS_HEADERS)
987988
headers["Cookie"] = "; ".join([f"{k}={v}" for k, v in self.cookies.items()])
988989
req = urllib.request.Request(url + "?" + params_str, headers=headers, method="GET") # type: ignore
989-
resp = urllib.request.urlopen(req) # type: ignore
990-
991-
# Error: "user is not authorized"
992-
# This error occurs when the method is called by too many times
993-
if resp.status != 200:
994-
time.sleep(2)
995-
continue
996-
997-
info = json.loads(resp.read())
998-
999-
# This error is gotten when remote path is blocked
1000-
if info.get("host") == "issuecdn.baidupcs.com":
1001-
return None
1002-
1003-
if not info.get("urls"):
990+
try:
991+
resp = urllib.request.urlopen(req) # type: ignore
992+
993+
# Error: "user is not authorized"
994+
# This error occurs when the method is called by too many times
995+
if resp.status != 200:
996+
time.sleep(2)
997+
continue
998+
999+
info = json.loads(resp.read())
1000+
1001+
# This error is gotten when remote path is blocked
1002+
if info.get("host") == "issuecdn.baidupcs.com":
1003+
return None
1004+
1005+
if not info.get("urls"):
1006+
return None
1007+
else:
1008+
# return info["urls"][0]["url"].replace("&htype=", "")
1009+
return info["urls"][0]["url"]
1010+
except urllib.error.HTTPError as e:
1011+
print(f"Error Code:{e.code}")
10041012
return None
1005-
else:
1006-
# return info["urls"][0]["url"].replace("&htype=", "")
1007-
return info["urls"][0]["url"]
10081013

10091014
def file_stream(
10101015
self,

0 commit comments

Comments
 (0)