处理IncompleteRead,URLError

fro*_*e__ 7 python error-handling urllib2 httplib

它是一个Web挖掘脚本.

def printer(q,missing):
    while 1:
        tmpurl=q.get()
        try:
            image=urllib2.urlopen(tmpurl).read()
        except httplib.HTTPException:
            missing.put(tmpurl)
            continue
        wf=open(tmpurl[-35:]+".jpg","wb")
        wf.write(image)
        wf.close()
Run Code Online (Sandbox Code Playgroud)

q是一个Queue()由Urls组成的``缺少一个空队列来收集错误提升网址

它由10个线程并行运行.

每次我跑这个,我得到了这个.

  File "C:\Python27\lib\socket.py", line 351, in read
    data = self._sock.recv(rbufsize)
  File "C:\Python27\lib\httplib.py", line 541, in read
    return self._read_chunked(amt)
  File "C:\Python27\lib\httplib.py", line 592, in _read_chunked
    value.append(self._safe_read(amt))
  File "C:\Python27\lib\httplib.py", line 649, in _safe_read
    raise IncompleteRead(''.join(s), amt)
IncompleteRead: IncompleteRead(5274 bytes read, 2918 more expected)
Run Code Online (Sandbox Code Playgroud)

但我确实使用了except......我尝试过其他类似的东西

httplib.IncompleteRead
urllib2.URLError
Run Code Online (Sandbox Code Playgroud)

甚至,

image=urllib2.urlopen(tmpurl,timeout=999999).read()
Run Code Online (Sandbox Code Playgroud)

但这都不起作用..

我怎么能抓住IncompleteReadURLError

Mic*_*ard 0

我认为这个问题的正确答案取决于您对“引发错误的 URL”的看法。

捕获多个异常的方法

如果您认为任何引发异常的 URL 都应该添加到队列中,missing那么您可以执行以下操作:

try:
    image=urllib2.urlopen(tmpurl).read()
except (httplib.HTTPException, httplib.IncompleteRead, urllib2.URLError):
    missing.put(tmpurl)
    continue
Run Code Online (Sandbox Code Playgroud)

这将捕获这三个异常中的任何一个并将该 url 添加到队列中missing。更简单地你可以这样做:

try:
    image=urllib2.urlopen(tmpurl).read()
except:
    missing.put(tmpurl)
    continue
Run Code Online (Sandbox Code Playgroud)

捕获任何异常,但这不被视为 Pythonic,并且可能隐藏代码中其他可能的错误。

如果“错误引发 URL”指的是任何引发httplib.HTTPException错误的 URL,但在收到其他错误时您仍希望继续处理,那么您可以执行以下操作:

try:
    image=urllib2.urlopen(tmpurl).read()
except httplib.HTTPException:
    missing.put(tmpurl)
    continue
except (httplib.IncompleteRead, urllib2.URLError):
    continue
Run Code Online (Sandbox Code Playgroud)

missing这只会在引发 时将 URL 添加到队列中httplib.HTTPException,否则会捕获httplib.IncompleteReadurllib.URLError防止脚本崩溃。

遍历队列

顺便说一句,while 1循环总是让我有点担心。您应该能够使用以下模式循环遍历队列内容,尽管您可以继续按照自己的方式进行操作:

for tmpurl in iter(q, "STOP"):
    # rest of your code goes here
    pass
Run Code Online (Sandbox Code Playgroud)

安全地处理文件

另一方面,除非绝对有必要这样做,否则您应该使用上下文管理器来打开和修改文件。所以你的三个文件操作行将变成:

with open(tmpurl[-35:]+".jpg","wb") as wf:
    wf.write()
Run Code Online (Sandbox Code Playgroud)

上下文管理器负责关闭文件,即使在写入文件时发生异常也会这样做。