2

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

电影的标题、年份、评级、年龄评级​​和概要。

我根本不想使用外部模块,只使用 Python 3.4 附带的模块。

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

我该怎么做?

4

2 回答 2

1

这是取自此处的示例:

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'}]
于 2014-03-29T17:52:54.917 回答
0

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

    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() 会返回字符串中第一个字母的位置。

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

于 2014-03-29T20:48:07.323 回答