How to handle IncompleteRead: in python

后端 未结 8 1660
面向向阳花
面向向阳花 2020-12-05 10:12

I am trying to fetch some data from a website. However it returns me incomplete read. The data I am trying to get is a huge set of nested links. I did some rese

8条回答
  •  臣服心动
    2020-12-05 10:27

    What worked for me is catching IncompleteRead as an exception and harvesting the data you managed to read in each iteration by putting this into a loop like below: (Note, I am using Python 3.4.1 and the urllib library has changed between 2.7 and 3.4)

    try:
        requestObj = urllib.request.urlopen(url, data)
        responseJSON=""
        while True:
            try:
                responseJSONpart = requestObj.read()
            except http.client.IncompleteRead as icread:
                responseJSON = responseJSON + icread.partial.decode('utf-8')
                continue
            else:
                responseJSON = responseJSON + responseJSONpart.decode('utf-8')
                break
    
        return json.loads(responseJSON)
    
    except Exception as RESTex:
        print("Exception occurred making REST call: " + RESTex.__str__())
    

提交回复
热议问题