Trouble With Python Code
Question: I am taking the introduction to computer science class at Udacity and for one
of the assignments I must write code that will take all the links from a
webpage. Here is the code

    
    
    def get_next_target(page):
        start_link = page.find('<a href=')
        while True:
            if start_link == -1:
                x, y = None, 0
                return x, y
                break
        start_quote = page.find('"', start_link)
        end_quote = page.find('"', start_quote + 1)
        url = page[start_quote + 1:end_quote]
        return url, end_quote
    

When I run samples, it seems to work, but when I submit my code, I get the
result that my submission did not terminate. What does this mean? What is the
issue with my code?


Answer: 
    def get_next_target(page, start=0):
        """ function find link in part of page """
        start_link = page[start:].find('<a href=')
        if start_link == -1:
            x, y = None, None
            return x, y
        start_quote = page.find('"', start_link)
        end_quote = page.find('"', start_quote + 1)
        url = page[start_quote + 1:end_quote]
        return url, end_quote
    
    def find_all(page):
        """ function find all links"""
        length = len(page)
        current_position = 0  # we start with full page
        urls = []
        while current_position < length:
            # get url and set current_positon, so next we gonna search 
            # only part of page
            url, current_position = get_next_target(page, current_position)
            urls.append(url)
            if current_position is None:
                return urls
        return urls
    

But I would recommand use regular expressions - something like:

    
    
    def find_all(page):
        import re
        return re.findall('<a href="(.+)"', page)
    

**Edit:** But neither solution will detect links like:

    
    
    <a  href="some/page">, or <a tilte="ti" href="some/page" >
    

for this you will need recreate the regular expression. It is the best option
IMHO.

