我是Python的新手。每当我使用Try时,就会出现NameError。没有异常处理时,它可以完美工作。
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
try:
htm = urlopen('https://uiit.tech/placements/placements.pp')
except HTTPError as e:
print(e)
bs = BeautifulSoup(htm, 'html.parser')
print(bs.h1)
输出错误
HTTP Error 404: Not Found
Traceback (most recent call last):line 12, in <module>
bs = BeautifulSoup(htm.read(), 'html.parser')
NameError: name 'htm' is not defined
答案 0 :(得分:0)
尝试做:
except urllib.error.HTTPError as e:
print(e)
答案 1 :(得分:0)
您在
上犯了错误htm = urlopen('https://uiit.tech/placements/placements.pp')
这应该是:
htm = urlopen('https://uiit.tech/placements/placements.php')
答案 2 :(得分:0)
您想尝试在htm
部分中使用try
。当前,由于异常,它从未设置。
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
try:
htm = urlopen('https://uiit.tech/placements/placements.pp')
bs = BeautifulSoup(htm, 'html.parser')
print(bs.h1)
except HTTPError as e:
print(e)