接下来如何创建条件,即使错误是 "the index out of range"
How to create condition next even the error is "the index out of range"
这是我第一次使用 python,我还在学习 python。我在尝试使用索引时遇到问题。索引显示错误 "IndexError: list index out of range"。但我想通过或为它创造条件。像这样的例子:
links = "http://www.website_name.com/"
content_ig = BeautifulSoup(send.content, 'html.parser')
script = content_ig.find_all("script")[3].get_text()
script = script.split('openData = ')[1][:-1]
if not script:
#This condition i create to next if the value is out of index
else:
print("Works")
我的意思是当索引超出范围时,我想在另一个值旁边创建条件,而不仅仅是停止并显示错误 "IndexError: list index out of range"。
为了解决您的问题,您可以将代码行包裹在 try-except
大括号内:
try:
script = script.split('openData = ')[1][:-1]
print("Works")
except IndexError:
... # code to run if the value is out of index
快速演示:
In [1739]: x = [0]
In [1740]: try:
...: print(x[1]) # only 1 element in x, so this is invalid
...: except IndexError:
...: print("List out of range!")
...:
List out of range!
这是我第一次使用 python,我还在学习 python。我在尝试使用索引时遇到问题。索引显示错误 "IndexError: list index out of range"。但我想通过或为它创造条件。像这样的例子:
links = "http://www.website_name.com/"
content_ig = BeautifulSoup(send.content, 'html.parser')
script = content_ig.find_all("script")[3].get_text()
script = script.split('openData = ')[1][:-1]
if not script:
#This condition i create to next if the value is out of index
else:
print("Works")
我的意思是当索引超出范围时,我想在另一个值旁边创建条件,而不仅仅是停止并显示错误 "IndexError: list index out of range"。
为了解决您的问题,您可以将代码行包裹在 try-except
大括号内:
try:
script = script.split('openData = ')[1][:-1]
print("Works")
except IndexError:
... # code to run if the value is out of index
快速演示:
In [1739]: x = [0]
In [1740]: try:
...: print(x[1]) # only 1 element in x, so this is invalid
...: except IndexError:
...: print("List out of range!")
...:
List out of range!