Issue
it's my first time using python, and i still learn about python. I have problem when i tried to using index. Index show the error "IndexError: list index out of range". But i want to pass or create condition next for it. Example like this :
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")
I mean when the index out of the range, i want create condition the next to another value, not just stop and show the error "IndexError: list index out of range".
Solution
To address your question, you can wrap your line of code inside a try-except
brace:
try:
script = script.split('openData = ')[1][:-1]
print("Works")
except IndexError:
... # code to run if the value is out of index
Quick demo:
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!
Answered By - cs95
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.