Python urllib2,如何避免错误 - 需要帮助
我正在使用Python的urllib2库从网上下载网页。我没有使用任何用户代理之类的东西。下面是我遇到的一些错误示例。有没有简单的方法可以避免这些错误呢?
http://www.rottentomatoes.com/m/foxy_brown/
The server couldn't fulfill the request.
Error code: 403
http://www.spiritus-temporis.com/marc-platt-dancer-/
The server couldn't fulfill the request.
Error code: 503
http://www.golf-equipment-guide.com/news/Mark-Nichols-(golfer).html!!
The server couldn't fulfill the request.
Error code: 500
http://www.ehx.com/blog/mike-matthews-in-fuzz-documentary!!
We failed to reach a server.
Reason: timed out
IncompleteRead(5621 bytes read)
Traceback (most recent call last):
File "download.py", line 43, in <module>
localFile.write(response.read())
File "/usr/lib/python2.6/socket.py", line 327, in read
data = self._sock.recv(rbufsize)
File "/usr/lib/python2.6/httplib.py", line 517, in read
return self._read_chunked(amt)
File "/usr/lib/python2.6/httplib.py", line 563, in _read_chunked
raise IncompleteRead(value)
IncompleteRead: IncompleteRead(5621 bytes read)
谢谢
Bala
2 个回答
0
对于那些比较复杂的任务,你可能需要考虑使用一些工具,比如 mechanize、twill,甚至是 Selenium 或 Windmill。这些工具可以处理更复杂的情况,比如支持 cookies 或者 JavaScript。
如果是随机的网站,仅仅使用 urllib2 可能会有点麻烦(比如需要处理签名的 cookies)。
0
很多网站在访问时需要一些特殊的“饼干”(也就是cookie)或者其他的身份验证,如果你看到403这个状态码,很可能就是因为这个原因。
503错误通常意味着你在快速地从服务器请求资源,可能是因为你一直在重复请求,这时候你需要稍等一下再试。
500这个错误看起来根本就不存在……
关于超时错误,可能不需要加“!!”,我可以在不加的情况下加载资源。
我建议你去了解一下HTTP状态码。