爱奇艺
1 import time
2 import traceback
3 import requests
4 from lxml import etree
5 import re
6 from bs4 import BeautifulSoup
7 from lxml.html.diff import end_tag
8 import json
9 import pymysql
10 #连接数据库 获取游标
11 def get_conn():
12 """
13 :return: 连接,游标
14 """
15 # 创建连接
16 conn = pymysql.connect(host="82.157.112.34",
17 user="root",
18 password="root",
19 db="MovieRankings",
20 charset="utf8")
21 # 创建游标
22 cursor = conn.cursor() # 执行完毕返回的结果集默认以元组显示
23 if ((conn != None) & (cursor != None)):
24 print("数据库连接成功!游标创建成功!")
25 else:
26 print("数据库连接失败!")
27 return conn, cursor
28 #关闭数据库连接和游标
29 def close_conn(conn, cursor):
30 if cursor:
31 cursor.close()
32 if conn:
33 conn.close()
34 return 1
35 def get_iqy():
36 # 获取数据库总数据条数
37 conn, cursor = get_conn()
38 sql = "select count(*) from movieiqy"
39 cursor.execute(sql) # 执行sql语句
40 conn.commit() # 提交事务
41 all_num = cursor.fetchall()[0][0] #cursor 返回值的类型是一个元祖的嵌套形式 比如( ( ) ,)
42 pagenum=int(all_num/48)+1 #这里是计算一个下面循环的起始值 每48个电影分一组
43 # print(pagenum)
44 print("movieiqy数据库有", all_num, "条数据!")
45
46
47 url = "https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=1&ret_num=48&session=ee4d98ebb4e8e44c8d4b14fa90615fb7"
48 headers = {
49 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
50 }
51 # response=requests.get(url=url,headers=headers)
52 # response.encoding="utf-8"
53 # page_text=response.text
54 # print(page_text)
55 """
56 """
57 #
58 temp_list = [] #暂时存放单部电影的数据
59 dataRes = [] #每次循环把单部电影数据放到这个list
60 for i in range(1, 137): #循环1-136 第137 json 是空的 也就是全部爬完
61 url = "https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=1&ret_num=48&session=ee4d98ebb4e8e44c8d4b14fa90615fb7"
62 url_0 = "https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id="
63 url_0 = url_0 + str(i) + "&ret_num=48&session=ad1d98bb953b7e5852ff097c088d66f2"
64 print(url_0) #输出拼接好的url
65 response = requests.get(url=url_0, headers=headers)
66 response.encoding = "utf-8"
67 try:
68 page_text = response.text
69 #解析json对象
70 json_obj = json.loads(page_text)
71 #这里的异常捕获是因为 测试循环的次数有可能超过电影网站提供的电影数 为了防止后续爬到空的json对象报错
72 json_list = json_obj["data"]["list"]
73 except:
74 print("捕获异常!")
75 return dataRes #json为空 程序结束
76 for j in json_list: # 开始循环遍历json串
77 # print(json_list)
78 name = j["name"] #找到电影名
79 print(name)
80 temp_list.append(name)
81 #异常捕获,防止出现电影没有评分的现象
82 try:
83 score = j["score"] #找到电影评分
84 print(score)
85 temp_list.append(score)
86 except KeyError:
87 print( "评分---KeyError")
88 temp_list.append("iqy暂无评分") #替换字符串
89
90 link = j["playUrl"] #找到电影链接
91 temp_list.append(link)
92 # 解析播放状态
93 """
94 独播:https://www.iqiyipic.com/common/fix/site-v4/video-mark/only.png
95 VIP:https://pic0.iqiyipic.com/common/20171106/ac/1b/vip_100000_v_601_0_21.png
96 星钻:https://www.iqiyipic.com/common/fix/site-v4/video-mark/star-movie.png
97 """
98 state = []
99 pay_text = j["payMarkUrl"] #因为播放状态只有在一个图片链接里有 所以需要使用re解析出类似vip和only(独播)的字样
100 print(pay_text)
101 if (len(pay_text) == 0): #如果没有这个图片链接 说明电影是免费播放
102 state="免费"
103 else:
104 find_state = re.compile("(.*?).png")
105 state = re.findall(find_state, pay_text) #正则匹配链接找到vip
106 # print(state[0])
107
108 if(len(state)!=0): #只有当链接不为空再执行
109 # print(state)
110 # 再次解析
111 part_state=str(state[0])
112 part_state=part_state.split("/")
113 print(part_state[-1])
114 state = part_state[-1][0:3] #字符串分片
115 # 这里只输出了三个字符,如果是独播,页面显示的是only,我们设置为”独播“
116 if (state == "onl"):
117 state = "独播"
118 if (state == "sta"):
119 state = "星钻"
120 if(state == "vip"):
121 state="VIP"
122 print(state)
123 # 添加播放状态
124 # print(state)
125 temp_list.append(state)
126 dataRes.append(temp_list)
127 # print(temp_list)
128 temp_list = []
129
130 print("___________________________")
131 return dataRes
132
133 def insert_iqy():
134 cursor = None
135 conn = None
136 try:
137 count=0
138 list = get_iqy()
139 print(f"{time.asctime()}开始插入爱奇艺电影数据")
140 conn, cursor = get_conn()
141 sql = "insert into movieiqy (id,name,score,path,state) values(%s,%s,%s,%s,%s)"
142 for item in list:
143 print(item)
144 count = count + 1
145 if (count % 48 == 0):
146 print("___________________________")
147 #异常捕获,防止数据库主键冲突
148 try:
149 cursor.execute(sql, [0, item[0], item[1], item[2], item[3] ])
150 except pymysql.err.IntegrityError:
151 print("重复!跳过!")
152
153 conn.commit() # 提交事务 update delete insert操作
154 print(f"{time.asctime()}插入爱奇艺电影数据完毕")
155 except:
156 traceback.print_exc()
157 finally:
158 close_conn(conn, cursor)
159 return;
160
161 if __name__ == "__main__":
162 # get_iqy()
163 insert_iqy()
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 »
Python爬虫爬取爱奇艺、腾讯视频电影相关信息(改进版)-