【问题标题】:Finding information on a website without an external module在没有外部模块的网站上查找信息
【发布时间】:2014-05-09 03:44:23
【问题描述】:

我正在用 Python 创建一个程序,您可以在其中搜索电视节目/电影,并从 IMDb 中为您提供:

电影的标题、年份、分级、年龄分级和剧情简介。

我想完全不使用外部模块,只使用 Python 3.4 附带的那些。

我知道我将不得不使用 urllib,但我不知道从那里去哪里。

我该怎么做?

【问题讨论】:

  • 为什么要随意限制?到目前为止,您自己尝试过什么?您对 HTML 解析了解多少,您是否看过 IMDb 是否提供 API?
  • Does IMDB provide an API? 列出了几个选项,您只需导入 json 模块来处理返回的数据。
  • 我使用了this,并要求用户输入电影名称。然后我做url = urllib.request.urlopen("http://www.omdbapi.com/?t="+title+"&r=XML"),我将如何从那里提取信息?

标签: python imdb python-3.4


【解决方案1】:

这可能太复杂了,但是: 我看网页代码。我查看我想要的信息在哪里,然后提取信息。

    import urllib.request

def search(title):
    html = urllib.request.urlopen("http://www.imdb.com/find?q="+title).read().decode("utf-8")
    f=html.find("<td class=\"result_text\"> <a href=\"",0)+34
    openlink=""
    while html[f]!="\"":
        openlink+= html[f]
        f+=1
    html = urllib.request.urlopen("http://www.imdb.com"+openlink).read().decode("utf-8")
    f = html.find("<meta property='og:title' content=\"",0)+35
    titleyear=""
    while html[f] !="\"":
        titleyear+=html[f]
        f+=1

    f = html.find("title=\"Users rated this ",0)+24
    rating = ""
    while html[f] !="/":   
        rating+= html[f]
        f+=1

    f=html.find("<meta name=\"description\" content=\"",0)+34
    shortdescription = ""
    while html[f] !="\"":
        shortdescription+=html[f]
        f+=1
    print (titleyear,rating,shortdescription)
    return (titleyear,rating,shortdescription)
search("friends")

添加到 f 的数字必须恰到好处,您计算正在搜索的字符串的长度,因为 find() 会返回字符串中第一个字母的位置。

看起来很糟糕,还有其他更简单的方法吗?

【讨论】:

    【解决方案2】:

    这是取自from here的例子:

    import json
    from urllib.parse import quote
    from urllib.request import urlopen
    
    def search(title):
        API_URL = "http://www.omdbapi.com/?r=json&s=%s"
        title = title.encode("utf-8")
        url = API_URL % quote(title)
        data = urlopen(url).read().decode("utf-8")
        data = json.loads(data)
        if data.get("Response") == "False":
            print(data.get("Error", "Unknown error"))
    
        return data.get("Search", [])
    

    那么你可以这样做:

    >>> search("Idiocracy")
    [{'Year': '2006', 'imdbID': 'tt0387808', 'Title': 'Idiocracy'}]
    

    【讨论】:

    • 哇,谢谢。当我尝试让用户输入电影名称时,我输入search(movieTitle),它不会加载信息。有没有办法做到这一点?另外,有没有加载评级等?
    • "它不加载信息"??什么信息?你有错误吗?
    • 当我让用户输入电影名称时,它不会打印出[{'Year': '2006', 'imdbID': 'tt0387808', 'Title': 'Idiocracy'}]
    • 这表明您的代码接受用户输入存在问题。
    猜你喜欢
    • 2020-07-07
    • 2012-07-05
    • 1970-01-01
    • 2023-04-03
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多