python爬虫—URLError的使用,能够看到结果是404,还是超时
from urllib.request import Request,urlopen
from fake_useragent import UserAgent
from urllib.error import URLError
url ="https://www.baidu123.comasda/"
headers = {
"User-Agent":UserAgent().chrome
}
try:
request = Request(url,headers= headers)
response = urlopen(request)
print(response.read().decode())
except URLError as e :
if e.args == ():
print(e.code)#404和超时
else:
print(e.args[0].errno)
print(e)

本文介绍了如何在Python爬虫中使用`urllib`库处理URL错误,特别是`URLError`异常。示例代码展示了当尝试访问不存在的网址(如404错误)或网络超时时,如何捕获并打印相应的错误信息。通过设置`User-Agent`以避免被网站屏蔽,并使用`try-except`结构来处理异常。
1473

被折叠的 条评论
为什么被折叠?



