[英]Try-Catch with Beatifulsoup
So essentially the program I am making is going to grab lyrics out of the genius website for any song the user chooses.所以本质上,我正在制作的程序将从天才网站中抓取用户选择的任何歌曲的歌词。
Now the problem I am having is that when I run my program sometimes the lyrics show up, and sometimes they don't and I'm met with an attribute none-type error.现在我遇到的问题是,当我运行我的程序时,有时会出现歌词,有时它们不会出现,我遇到了属性无类型错误。
Now I've tried everything I tried using headers which made the none-type error occur more frequently, and even selenium to webscrape but the none-type still occured.现在我已经尝试了所有我尝试使用的标题,这使得非类型错误更频繁地发生,甚至 selenium 到 webscrape 但仍然发生非类型错误。
Anyways since I can't get rid of it, I thought of using a try catch error block so that when the non-type error does occur it can just try again.无论如何,因为我无法摆脱它,我想到了使用 try catch 错误块,这样当非类型错误确实发生时,它可以重试。
Now the problem I am having with my try-catch block is that when the none-type error occurs it just goes on an infinite loop, until python gives me the stackoverflow error.现在我的 try-catch 块遇到的问题是,当发生非类型错误时,它只会进入无限循环,直到 python 给我 stackoverflow 错误。
For example I put "loading..." when the none-type error would occur and it just infite loops the "loading...", so how can I fix this error.例如,当发生非类型错误并且它只是无限循环“正在加载...”时,我输入了“正在加载...”,那么我该如何解决这个错误。 Any advice would be apperciated.
任何建议都会受到重视。
SongURL = f"https://genius.com{picking()}{token}"
Res_1 = requests.get(SongURL)
soup = BeautifulSoup(Res_1.text, "html5lib")
while True:
try:
lyrics = soup.find("div", class_="lyrics").get_text()
print(lyrics)
break
except Exception:
print("Loading...")
continue
The problem is that you included a continue
within the except
part of the block.问题是您在块的
except
部分中包含了continue
。 Catching the exception is the mechanism to tell Python what to do when a problem occurs.捕获异常是告诉 Python 在出现问题时该怎么做的机制。 When you tell it to
continue
within a while True
, you're telling it to continue with the loop.当您告诉它在一段时间内
continue
while True
时,您是在告诉它继续循环。
I would instead insert another break
, and remove the continue
.相反,我会插入另一个
break
,并删除continue
。 Or, perhaps it's better to re-evaluate whether you need the while
loop in the first place.或者,也许最好重新评估您是否首先需要
while
循环。 If the goal is simply to retrieve the lyrics once, the loop shouldn't be necessary.如果目标只是检索歌词一次,则不需要循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.