python - Beautifulsoup,达到最大递归深度

标签 python beautifulsoup

这是一个 beautifulsoup在所有 <p> 中获取内容的程序html标签。从某些网页抓取内容后,我收到一条错误消息,指出超出了最大递归深度。

def printText(tags):
    for tag in tags:
        if tag.__class__ == NavigableString:
            print tag,
        else:
            printText(tag)
    print ""
#loop over urls, send soup to printText procedure

痕迹的底部:

 File "web_content.py", line 16, in printText
    printText(tag)
  File "web_content.py", line 16, in printText
    printText(tag)
  File "web_content.py", line 16, in printText
    printText(tag)
  File "web_content.py", line 16, in printText
    printText(tag)
  File "web_content.py", line 16, in printText
    printText(tag)
  File "web_content.py", line 13, in printText
    if tag.__class__ == NavigableString:
RuntimeError: maximum recursion depth exceeded in cmp

最佳答案

如果您的 printText() 遇到 NavigableString 以外的任何内容,它会递归调用自身。这包括 NavigableString 的子类,例如 Comment。对评论调用 printText() 会迭代评论的文本,并导致您看到的无限递归。

我建议在您的 if 语句中使用 isinstance() 而不是比较类对象:

if isinstance(tag, basestring):

我通过在递归之前插入打印语句来诊断这个问题:

print "recursing on", tag, type(tag)
printText(tag)

关于python - Beautifulsoup,达到最大递归深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10118160/

相关文章:

python - 如何使用 BeautifulSoup 选择 href 类标签?

python - Django:在传递的 View 中使用 HttpResponseRedirect(reverse()) 访问 kwargs

python循环并为列的每个值创建新的数据框

python - 从 for 循环写入文件

Python - 获取 URL、解析和打印 PDF

python - 从损坏的 html 标签中提取文本,并使用 <br> 分隔元素

python - 在python中的函数调用外部重印错误

python - 如何在Python中从数据包中获取IP地址?

python - 线程的单独工作路径?

Python - 在网站上搜索最优惠的价格