Python - Returning String with recursion

Viewed 47

The project that I am doing requires us to input a url and then follow the link in a particular position a number of number of times then return the last page visited. I have found the solution with a while loop, but now I am trying to do it with recursion. Example: http://py4e-data.dr-chuck.net/known_by_Fikret.html

Find the link at position 3 (the first name is 1). Follow that link. Repeat this process 4 times. The answer is the last name that you retrieve.

Sequence of names: Fikret Montgomery Mhairade Butchi Anayah

Last name in sequence: Anayah

My code is this so far:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
import re

cnt = input("Enter count:")
post = input("Enter position:")
url = "http://py4e-data.dr-chuck.net/known_by_Fikret.html"
count = int(cnt)
position = int(post)

def GetLinks(initalPage, position, count):
    html = urlopen(initalPage).read()
    soup = BeautifulSoup(html, "html.parser")
    temp = ""
    links = list()
    tags = soup('a')
    for tag in tags:
        x = tag.get('href', None)
        links.append(x)
    print(links[position - 1])
    if count > 1:
        GetLinks(links[position-1], position, count - 1)
    return links[position - 1]

y = GetLinks(url, position, count)
print("****", y)

I see two problems with my code.

I am creating a list that is expanding with every recursion, which makes it very hard to locate the proper value.

Second, I am obviously returning the wrong item.

I don't know exactly how to fix this.

0 Answers
Related