Python程序不返回http://xkcd.com/353(Udacity Intro到CS课程)的链接

时间:2016-08-19 18:40:17

标签: python-3.x search computer-science

def get_page(url):
    try:
        import urllib
        return urllib.urlopen(url).read()
    except:
        return "error"


def get_next_target(page):
    start_link = page.find('<a href=')

    if start_link == -1:
        return None, 0
    else:
        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 print_all_links(page):
    while True:
        url, endpos = get_next_target(page)
        if url:
            print(url)
            page = page[endpos:]
        else:
            break

print_all_links(get_page('http://xkcd.com/353'))

我通过了所有测验,但def get_page没有显示在视频上,但代码是在视频下方的长句中给出的。 但是,如果它们在最后一行print_all_links('string')中作为字符串输入,它会打印链接。

1 个答案:

答案 0 :(得分:1)

我发现我之前发布的上述代码在Python 2中有效,但不是Python 3.我更改了导入并返回def get_page(url)以反映Py3要求并添加了.decode('utf-8' )修复了TypeError:需要一个类似字节的对象,而不是'str'

def get_page(url):
try:
    import urllib.request
    return urllib.request.urlopen(url).read().decode('utf-8')
except:
    return "error"