How to Improve my Code On Python Like Avoiding Index Out of Range Etc

Question:

                a = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")[1]
                b = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")[2]
                c = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")[3]

                
                for val1,val2,val3 in zip(a,b,c):
                    try:
                        cast_data.append(val1.get_text())
                        cast_data.append(val2.get_text())
                        cast_data.append(val3.get_text())

                    except:
                        continue
                data.append(cast_data)
                
                dataFrame = pd.DataFrame(data = data)
                dataFrame.to_csv('sssssssssssss.csv')
                print (dataFrame)

Stress! Can you help me out?
My BIG problem is when the index 1 is missing im getting an error how to avoid those error out of range?

i want to improve my poor code please help me

Asked By: LegendCoder

||

Answers:

You can check the number of items before accessing to each items in the list:

items = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")

if len(items) < 3:
    return

a = items[1]
b = items[2]
c = items[3]

...
Answered By: shiumachi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.