Newbie1
Newbie1

Reputation: 29

Python beautifulSoup loops

I'm trying to assign the URL from a specific iteration (in the 'position' variable) of a for loop to a variable using BeautifulSoup, and I can't see why it's not working (the output is the full list - I only want the selected one). Any help wld much appreciated. Thanks!

position = int(input('Enter position:'))
n = int(0)

tags = soup('a')
for tag in tags:
    if n<position:
        n=n+1
    else:
        x=tag.get('href', None)
        print(x)

Upvotes: 0

Views: 48

Answers (1)

QHarr
QHarr

Reputation: 84465

You could avoid a loop and pass position as value for limit argument with .select() method of soup object.

select returns a list of elements matched by the css selector list passed in e.g. anchor tags selected by a type selector. limit stops matching at the specified number. -1 index returns last match from returned list i.e. at the desired position. 0-indexing.

position = int(input('Enter position:'))
result = soup.select('a', limit=position)[-1]['href']
print(result)

Upvotes: 2

Related Questions