报错:http.client.IncompleteRead: IncompleteRead(180224 bytes read, 39396 more exp

缺乏、安全感 2022-05-09 02:14 276阅读 0赞

在我爬取某网站时出现了该错误,但是只要重新运行一下程序还是请求成功。

我搜索了一下百度,没有发现类似的答案,不过在stackoverflow有类似的疑问。等会后面有链接。

可能出现这个问题的原因:这里执行urllib的read()函数时候,它会捕获任何不完整的读取异常。因此出现了报错。

我们可以不让它捕获异常,因此当读取链接的时候我们可以用try / catch来抛出异常。

我之前的一段代码,不完整。

  1. request = urllib.request.Request('https://****.org/'+ url)
  2. res = urllib.request.urlopen(request)
  3. buffer = res.read() #这里
  4. if os.path.isfile(r'E:\pythonxm\zhengze\%s.pdf'%(filename)):
  5. print("已存在%s文件" %(filename))
  6. i = i+1
  7. continue
  8. fo =open(filename+".pdf","wb+")
  9. fo.write(buffer)
  10. fo.close()
  11. i = i+1

改过之后:

  1. try: #添加了try语句
  2. buffer = res.read()
  3. except http_client.IncompleteRead as e:
  4. buffer = e.partial
  5. if os.path.isfile(r'E:\pythonxm\zhengze\%s.pdf'%(filename)):
  6. print("已存在%s文件" %(filename))
  7. i = i+1
  8. continue
  9. fo =open(filename+".pdf","wb+")
  10. fo.write(buffer)
  11. fo.close()
  12. i = i+1

我这里用的是python3,python2中的urllib2不能再使用,由urllib.request代替。

参考网页链接:https://stackoverflow.com/questions/14442222/how-to-handle-incompleteread-in-python

_______________________分割线——————————————————————————————

别人的类似文章,不知道有没有用,先记下链接,仅供参考:

此篇重在分析出错原因:https://blog.csdn.net/woshiaotian/article/details/40297239

这篇给出了其他的解决方案:https://blog.csdn.net/haoli001/article/details/40863433

—————————————————————————再次更新—————————

IncompleteRead打出这个关键字可以发现很多,,,,,,尴尬,,,,尴尬

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读