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(pagenum+1, pagenum+100): #循環100-1次
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 page_text = response.text 68 #解析json對象
69 json_obj = json.loads(page_text) 70 #這里的異常捕獲是因為 測試循環的次數有可能超過電影網站提供的電影數 為了防止后續爬到空的json對象報錯
71 try: 72 json_list = json_obj['data']['list'] 73 except KeyError: 74 return dataRes #json為空 程序結束
75 for j in json_list: # 開始循環遍歷json串
76 # print(json_list)
77 name = j['name'] #找到電影名
78 print(name) 79 temp_list.append(name) 80 #異常捕獲,防止出現電影沒有評分的現象
81 try: 82 score = j['score'] #找到電影評分
83 print(score) 84 temp_list.append(score) 85 except KeyError: 86 print( "KeyError") 87 temp_list.append("iqy暫無評分") #替換字符串
88
89 link = j['playUrl'] #找到電影鏈接
90 temp_list.append(link) 91 # 解析播放狀態
92 state = [] 93 pay_text = j['payMarkUrl'] #因為播放狀態只有在一個圖片鏈接里有 所以需要使用re解析出類似vip和only(獨播)的字樣
94 if (len(pay_text) == 0): #如果沒有這個圖片鏈接 說明電影是免費播放
95 state="免費"
96 else: 97 find_state = re.compile("(.*?).png") 98 state = re.findall(find_state, pay_text) #正則匹配鏈接找到vip
99 if(len(state)!=0): #只有當鏈接不為空再執行
100 # print(state)
101 # 再次解析
102 state = state[0][0:3] #字符串分片
103
104 # 這里只輸出了三個字符,如果是獨播,頁面顯示的是only,我們設置為”獨播“
105 if (state == "onl"): 106 state = "獨播"
107 else: 108 state = "VIP"
109 # print(state)
110 # 添加播放狀態
111 temp_list.append(state) 112 dataRes.append(temp_list) 113 # print(temp_list)
114 temp_list = [] 115
116 print('___________________________') 117 return dataRes 118
119 def insert_iqy(): 120 cursor = None 121 conn = None 122 try: 123 count=0 124 list = get_iqy() 125 print(f"{time.asctime()}開始插入愛奇藝電影數據") 126 conn, cursor = get_conn() 127 sql = "insert into movieiqy (id,name,score,path,state) values(%s,%s,%s,%s,%s)"
128 for item in list: 129 print(item) 130 count = count + 1
131 if (count % 48 == 0): 132 print('___________________________') 133 #異常捕獲,防止數據庫主鍵沖突
134 try: 135 cursor.execute(sql, [0, item[0], item[1], item[2], item[3] ]) 136 except pymysql.err.IntegrityError: 137 print("重復!跳過!") 138
139 conn.commit() # 提交事務 update delete insert操作
140 print(f"{time.asctime()}插入愛奇藝電影數據完畢") 141 except: 142 traceback.print_exc() 143 finally: 144 close_conn(conn, cursor) 145 return; 146
147 if __name__ == '__main__': 148 # get_iqy()
149 insert_iqy()
數據獲取方式:微信搜索關注【靠譜楊閱讀人生】回復【電影】。
整理不易,資源付費,謝謝支持。