Heim  >  Artikel  >  Backend-Entwicklung  >  Python3获取大量电影信息

Python3获取大量电影信息

高洛峰
高洛峰Original
2016-10-29 10:44:172103Durchsuche

实验室这段时间要采集电影的信息,给出了一个很大的数据集,数据集包含了4000多个电影名,需要我写一个爬虫来爬取电影名对应的电影信息。

 其实在实际运作中,根本就不需要爬虫,只需要一点简单的Python基础就可以了。

 前置需求:

Python3语法基础

HTTP网络基础

第一步,确定API的提供方。IMDb是最大的电影数据库,与其相对的,有一个OMDb的网站提供了API供使用。这家网站的API非常友好,易于使用。

http://www.omdbapi.com/

第二步,确定网址的格式。

1.png

第三步,了解基本的Requests库的使用方法。

http://cn.python-requests.org/zh_CN/latest/

1.png

为什么我要使用Requests,不使用urllib.request呢?

因为Python的这个库容易出各种各样的奇葩问题,我已经受够了……

 

第四步,编写Python代码。

我想做的是,逐行读取文件,然后用该行的电影名去获取电影信息。因为源文件较大,readlines()不能完全读取所有电影名,所以我们逐行读取。

import requests

for line in open("movies.txt"):
    s=line.split('%20\n')
    urll='http://www.omdbapi.com/?t='+s[0]
    result=requests.get(urll)
    if result:
        json=result.text
        print(json)
        p=open('result0.json','a')
        p.write(json)
        p.write('\n')
        p.close()

我预先把电影名文件全部格式化了一遍,将所有的空格替换成了"%20",便于使用API(否则会报错)。这个功能可以用Visual Studio Code完成。

1.png

注意,编码的时候选择GBK编码,不然会出现下面错误:

1 UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

第五步,做优化和异常处理。

主要做三件事,第一件事,控制API速度,防止被服务器屏蔽;

第二件事,获取API key(甚至使用多个key)

第三件事:异常处理。

import requests 3 
key=[‘’]

for line in open("movies.txt"):
    try:
        #……
    except TimeoutError:
        continue
    except UnicodeEncodeError:
        continue
    except ConnectionError:
        continue

下面贴出完整代码:

# -*- coding: utf-8 -*-

import requests
import time

key=['xxxxx','yyyyy',zzzzz','aaaaa','bbbbb']
i=0

for line in open("movies.txt"):
    try:
        i=(i+1)%5
        s=line.split('%20\n')
        urll='http://www.omdbapi.com/?t='+s[0]+'&apikey='+key[i]
        result=requests.get(urll)
        if result:
            json=result.text
            print(json)
            p=open('result0.json','a')
            p.write(json)
            p.write('\n')
            p.close()
            time.sleep(1)
    except TimeoutError:
        continue
    except UnicodeEncodeError:
        continue
    except ConnectionError:
        continue

接下来喝杯茶,看看自己的程序跑得怎么样吧!

1.png

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:python 序列化之JSON和pickle详解Nächster Artikel:Python字符串