我对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))
我的代码出了什么问题?你知道吗
这些行正在用没有
find
方法的HTML元素覆盖现有的soup
BeautifulSoup对象。这意味着soup.find
在第一次迭代之后,每次迭代都会失败。你知道吗尝试使用其他变量名。你知道吗
相关问题 更多 >
编程相关推荐