Leandro Poblet
Leandro Poblet

Reputation: 379

Unexpected python loop output

I'm working on a script to download the images from mangareader, and I've been trying to do it with Python since this is the first language I've learn throughly and I'm really into at the moment. The problem is that the output from the loop I've made is not working the way I was expecting to be.

soup = soup.findAll('option') # We select all the option tags
for l in soup: # And we start with a loop
    l = l.get_text()
    print l
    url = url + str(l)
    print url

The output I was expecting was:

1
http://www.mangareader.net/witch-shop/1/1
2
http://www.mangareader.net/witch-shop/1/2
3
http://www.mangareader.net/witch-shop/1/3
4
http://www.mangareader.net/witch-shop/1/4
5
http://www.mangareader.net/witch-shop/1/5
[...]

And what it shows is:

1
http://www.mangareader.net/witch-shop/1/1
2
http://www.mangareader.net/witch-shop/1/12
3
http://www.mangareader.net/witch-shop/1/123
4
http://www.mangareader.net/witch-shop/1/1234
5
http://www.mangareader.net/witch-shop/1/12345
[...]

And I can't figure out the why.

I appreciate your help.

Upvotes: 0

Views: 99

Answers (3)

Lev Levitsky
Lev Levitsky

Reputation: 65851

Well, on each iteration you do

url = url + str(l)

which appends digits to url, and it's never reset.

To get desired output, try

for l in soup:
    l = l.get_text()
    print l
    print url + str(l)

This way you don't change the contents of the url variable.

Upvotes: 3

wroniasty
wroniasty

Reputation: 8072

It's because you are appending l to url on every iteration without initializing url.

You should do:

#....
url2 = url + str(l)
print url2
#....

Upvotes: 2

Florin Stingaciu
Florin Stingaciu

Reputation: 8295

When you are doing the following

 url = url + str(l)

You are actually appending to the string, not adding 1 to it.

Upvotes: 1

Related Questions