Tokaalmighty Tokaalmighty -4 years ago 50
Python Question

Python / BeautifulSoup - Code showing IndexError

My code gives an IndexError. I am not able to figure out why. Please help.

This is my code:

import urllib
from bs4 import BeautifulSoup
url = ''

for i in range(7):
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

tags = soup('a')
lst = list()

for tag in tags:
a = tag.get('href',None)
url = lst[17]

print url

I get the following IndexError:

Traceback (most recent call last):
File "", line 15, in <module>
url = lst[17]
IndexError: list index out of range

What am I doing wrong? Thanks in advance.

Answer Source

You are not doing anything wrong, the code works OK for me. Maybe it is a network related problem in which the content of the page didn't load as it was supposed. Does the problem occur every time you run the code?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download