Python的最大遞歸深度錯誤 「max

  今天在寫爬蟲的時候,發現了一個事情,使用str方法強制轉換一個BeautifulSoup對象成字元串的時候報錯了,提示是「maximum recursion depth exceeded while calling a Python object」,意思大致是「當調用該對象超過最大遞歸深度」

  報錯如下:

  Traceback (most recent call last):    File "<stdin>", line 1, in <module>    File "C:Python27libsite-packagesbs4element.py", line 1045, in __str__      return self.encode()    File "C:Python27libsite-packagesbs4element.py", line 1055, in encode      u = self.decode(indent_level, encoding, formatter)    File "C:Python27libsite-packagesbs4element.py", line 1126, in decode      indent_contents, eventual_encoding, formatter)    File "C:Python27libsite-packagesbs4element.py", line 1195, in decode_contents      formatter))    File "C:Python27libsite-packagesbs4element.py", line 1126, in decode    ......        File "C:Python27libsite-packagesbs4element.py", line 1126, in decode      indent_contents, eventual_encoding, formatter)    File "C:Python27libsite-packagesbs4element.py", line 1195, in decode_contents      formatter))    File "C:Python27libsite-packagesbs4element.py", line 1098, in decode      text = self.format_string(val, formatter)    File "C:Python27libsite-packagesbs4element.py", line 163, in format_string      output = formatter(s)    File "C:Python27libsite-packagesbs4element.py", line 120, in substitute_xml      ns, EntitySubstitution.substitute_xml)    File "C:Python27libsite-packagesbs4element.py", line 104, in _substitute_if_appropriate      if (isinstance(ns, NavigableString)  RuntimeError: maximum recursion depth exceeded while calling a Python object

  而後我使用的ptpython並沒有報錯,直接通過了。

  其實原因是在Python里的遞歸調用是有限制的,可以使用sys模組里的getrecursionlimit方法查看的到,即(想深入的同學可以Google上搜索一番,這裡提供筆者所搜索到的https://cyrusin.github.io/2015/12/08/python-20151208/

sys.getrecursionlimit()

打開終端運行Python,可以看到默認限制值為1000

而ptpython里默認限制值為2000,這也不難解釋為什麼python下直接運行會報最大深度遞歸錯誤而ptpython可以正常運行了。

  那麼該來解決這個問題了,有get自然有set(當然還有其他方法比如達到深度限制時就做對應處理這方面不符合筆者目前需求,所以就不贅述,有需求的同學請自行Google百度一下),那麼設置最大深度限制的方法就是setrecursionlimit了,至於設置值為多少你自行設置了

sys.setrecursionlimit(2000)