Python 我应该在哪里使用什么异常?URLLib蟒蛇3
我有这个脚本爬网一个网站,并找到我需要的项目Python 我应该在哪里使用什么异常?URLLib蟒蛇3,python,exception,urllib,connection-timeout,Python,Exception,Urllib,Connection Timeout,我有这个脚本爬网一个网站,并找到我需要的项目 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))
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时,它会打印“发生了错误”
我知道我必须使用socket.timeout,但我应该将它放在代码中的什么位置?将urlopen调用包装为try:except调用:
try:
_URL = urlopen(req).read()
except Exception as e:
print("Something happened wrong: {}".format(e))
# do something, eg: continue
代码的其余部分会发生什么变化?如果我在那里抛出异常,那么下一行将在异常之后运行,在这里我定义了soup variable,这取决于您,但是请记住,您正在捕获异常,而不是抛出它(除非您愿意)。在循环中执行此操作时,请调用
continue
并继续执行下一个\u对象