1-2 用Python爬取猫眼票房网上的电影票房信息

 1 piaofang.py
 2 #-*- coding:utf-8 -*-
 3 '''
 4 该脚本可以抓取猫眼票房网站上的电影票房数据
 5 使用的数据为豆瓣上爬取的电影,见文件:doubanMovies_IMDBScore.csv
 6 '''
 7 import requests
 8 import lxml.html
 9 import time
10 from pandas import DataFrame
11 import pandas as pd
12 
13 headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}
14 def getDoc(url):
15     resp=requests.get(url,headers=headers)  #得到网页响应
16     time.sleep(0.1)   #暂停0.1秒,防止抓取太频繁被封IP
17     content=resp.text  #获取相应内容
18     doc = lxml.html.fromstring(content)
19     return doc
20 
21 #函数:输入为电影名字,输出为该电影在猫眼网上的票房
22 #说明:如果猫眼上没有该电影的信息,则标记:notfound
23 #如果猫眼上可以搜到该电影,但是没有票房数据,则标记:withoutData
24 def getPiaofang(title):
25     #根据电影名字形成猫眼上该电影的搜索结果页面
26     url = 'http://pf.maoyan.com/search?_v_=yes&key='+title
27     #由于编码格式比较混乱,所以此处尝试两种编码格式
28     try:
29         url=url.decode('gbk').encode('utf-8')
30     except:
31         url=url.encode('utf-8')
32     finally:
33         tempList=[]  #初始化函数中暂时用到的列表
34         doc=getDoc(url)  #解析网页
35         #抓取到的后缀名,可能为'万票房'、'人想看'、'暂无票房数据'
36         temp_back=doc.xpath('//*[@id="search-list"]/article/em/text()')
37         #某一部电影搜索结果页面,由于会有名字相近的电影会被搜索出来,所以要进行判断
38         temp_name=doc.xpath('//*[@id="search-list"]/article/div/text()')
39         if temp_name!=[]:  #首先结果页抓到的电影列表要不为空,即能搜索到该电影
40             #如果为空,则标记为'notfound'
41             for i in range(len(temp_name)):  #对搜索出的电影名字进行判定,取出与搜索的电影名字完全相同的一项
42                 temp1=(temp_name[i]).encode('utf-8')
43                 if temp1==title:  #如果循环到第i个名字,找到了与搜索的电影名字完全相同的一项,则接着对数字的后缀进行判断
44                     #如果没有找到与搜索的电影的名字完全相同的一项,则标记为'withoutData'
45                     temp2=unicode(temp_back[i]).encode('utf-8')
46                     if temp2=='万票房':  #如果后缀名为'万票房',则该数据可能就是我们要找的数据
47                         temp_num = doc.xpath('//*[@id="search-list"]/article['+str(i+1)+']/em/span/text()')
48                         if temp_num!=[]:  #如果可以抓取到数据,则转换为int类型后的数据即为所找的票房数据
49                             #如果抓取不到,则标记为'withoutData'
50                             print int(temp_num[0])
51                             tempList.append(int(temp_num[0]))
52                         else:
53                             tempList.append('withoutData')
54                     else:
55                         tempList.append('withoutData')
56                 else:
57                     tempList.append('withoutData')
58         else:
59             tempList.append('notfound')
60         return tempList[0]
61 
62 df=pd.read_csv('doubanMovies_IMDBScore.csv')  #打开豆瓣上爬取到的电影列表文件
63 piaofangList=[]  #初始化票房列表
64 errorNum=0  #初始化错误数
65 for i in range(0,len(df)):
66     try:
67         temp=df.ix[i,'title']
68         temp=temp.decode('gbk').encode('utf-8')  #进行编码格式转换
69         piaofangList.append(getPiaofang(temp))  #调用getPiaofang函数,得到票房数据
70     except:
71         errorNum+=1  #出错,则错误数加1
72         piaofangList.append('error')  #将票房数字标记为'error'
73         print 'error No.',errorNum
74     finally:
75         df1=DataFrame({'title':df.ix[:i,'title'],'piaofang':piaofangList})
76         df1.to_csv('test.csv',index=False)
77         print i+1  #打印标记
原文地址:https://www.cnblogs.com/PistonType/p/5499014.html