Python: 异常离开导致异常的行后重试

Python: retrying after exception is leaving the line that caused exception

我是 Python 的新手。我正在使用 BeautifulSoup - python 模块。如果存在,我必须找到并获取任何 ID 的文本,如 MathJax-Element-1, MathJax-Element-2, MathJax-Element-3, MathJax-Element-4,…. 等等。

我的密码是

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
attempts = 0
a=-1

while attempts < 100:
    try:
        a+=1
        math="MathJax-Element-"
        math +=`a`
        soup=(soup.find(id=math))
        print(soup.get_text())
        attempts = 0
    except AttributeError:
        attempts +=1

但在属性错误后代码失败。例如,如果没有 id MathJax-Element-2,那么我就不会得到后面有任何 id 的文本,比如 MathJax-Element-3 和 MathJax-Element-4

异常后尝试离开导致异常的行,即 soup=(soup.find(id=math))

我的代码出了什么问题?

    soup=(soup.find(id=math))
    print(soup.get_text())

这些行正在用 HTML 元素覆盖现有的 soup BeautifulSoup 对象,该元素没有 find 方法。这意味着 soup.find 将在第一次迭代后的每次迭代中始终失败。

尝试使用不同的变量名。

    element=(soup.find(id=math))
    print(element.get_text())