10

Python爬虫编程思想(14):网络爬虫中的异常处理

 3 years ago
source link: https://blog.csdn.net/nokiaguy/article/details/119268955
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

目录

1. URLError

2. HTTPError


         在前面的文章中详细讲解了发送请求的过程,但这是在正常情况下的使用。如果非正常使用,例如,提供的URL根本就是错的,那么在发送请求时就会抛出异常。如果不使用try...except语句,程序就会崩溃(俗称异常退出)。在使用try...except语句捕捉异常时,except子句通常会加上错误类型,以便我们清楚地了解发生了什么错误。这些异常类都在urllib的error模块中定义,主要有两个异常类:URLError和HTTPError。

1. URLError

        URLError类属于urllib库的error模块,该类从OSError类继承,是error模块中的异常基类,由request模块产生的异常都可以通过URLError来捕捉。

        URLError类有一个reason属性,可以通过这个属性获得错误的原因。

        下面的例子向不同服务器发送多个请求,并用URLError类捕捉发生的异常。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK