Python:在异常离开导致异常的行之后重试(Python: retrying after exception is leaving the line that caused exception)

编程入门 行业动态 更新时间:2024-10-18 20:30:16
Python:在异常离开导致异常的行之后重试(Python: retrying after exception is leaving the line that caused exception) python

我是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))

我的代码出了什么问题?

I am new to Python. I'm using BeautifulSoup - python module. I have to find and get text of any id like MathJax-Element-1, MathJax-Element-2, MathJax-Element-3, MathJax-Element-4,…. so on if it exists.

my code is

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

but after an attribute error the code fails. For example if there is no id MathJax-Element-2, then I am not getting text of any id following that, like MathJax-Element-3 and MathJax-Element-4

trying after exception is leaving the line that caused exception ie, soup=(soup.find(id=math))

What has gone wrong in my code?

最满意答案

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

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

尝试使用其他变量名称。

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

These lines are overwriting the existing soup BeautifulSoup object with an HTML element, which has no find method. This means that soup.find will always fail for every iteration after the first one.

Try using a different variable name.

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

更多推荐

本文发布于:2023-04-28 03:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329715.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   重试   行之   Python   retrying

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!