我应该在哪里使用什么异常?网址库 Python3

Where and What exception I should use ? URLLib Python3

我有这个脚本来抓取网站并找到我需要的项目..

from socket import timeout
from urllib.request import Request, urlopen, URLError
import bs4,urllib.parse
def track(self):
    for _object in _objects:
        req = Request('http://example.com/item.php?id='+str(_object))
        req.add_header('User-Agent',
                       'Mozilla 5.0')
        _URL = urlopen(req).read()
        soup = bs4.BeautifulSoup(_URL, "html.parser")
        allResults = []
        i = 1

        for hit in soup.findAll('cite'):
            if ("% Off" in hit.text):
                allResults.append(str(i) + ". " + hit.text + " | Item => " + _object)
                i += 1

        if (len(allResults) == 0):
            print("No result found for this item => " + _object)
        else:
            for element in allResults:
                print(element)

我想抛出一个异常,所以当连接到网站失败,或者由于任何其他原因无法到达 URL 时,它会打印 "Something happened wrong"

我知道我必须使用 socket.timeout 但我应该把它放在代码的什么地方?

将 urlopen 调用包装成一个 try:除了调用:

try: 
  _URL = urlopen(req).read()
except Exception as e:
  print("Something happened wrong: {}".format(e))
  # do something, eg: continue