BeautifulSoup 库 和 re 库 解析腾讯视频电影

  1 import requests
  2 import json
  3 from bs4 import BeautifulSoup       #网页解析获取数据
  4 import sys
  5 import re
  6 import urllib.request,urllib.error #制定url,获取网页数据
  7 import sqlite3
  8 import xlwt     #excel操作
  9 import time
 10 import pymysql
 11 import traceback
 12 #连接数据库  获取游标
 13 def get_conn():
 14     """
 15     :return: 连接,游标
 16     """
 17     # 创建连接
 18     conn = pymysql.connect(host="82.157.112.34",
 19                     user="root",
 20                     password="root",
 21                     db="MovieRankings",
 22                     charset="utf8")
 23     # 创建游标
 24     cursor = conn.cursor()  # 执行完毕返回的结果集默认以元组显示
 25     if ((conn != None) & (cursor != None)):
 26         print("数据库连接成功!游标创建成功!")
 27     else:
 28         print("数据库连接失败!")
 29     return conn, cursor
 30 #关闭数据库连接和游标
 31 def close_conn(conn, cursor):
 32     if cursor:
 33         cursor.close()
 34     if conn:
 35         conn.close()
 36     return 1
 37 
 38 #爬取腾讯视频电影数据
 39 def get_ten():
 40     conn,cursor=get_conn()
 41     sql="select count(*) from movieten"
 42     cursor.execute(sql)
 43     conn.commit()
 44     all_num=cursor.fetchall()[0][0]
 45 
 46     print("数据库有",all_num,"条数据!")
 47     #   https://v.qq.com/channel/movie?listpage=1&channel=movie&sort=18&_all=1&offset=0&pagesize=30
 48     url="https://v.qq.com/channel/movie?listpage=1&channel=movie&sort=18&_all=1"        #链接
 49     param={                                                                             #参数字典
 50         'offset':0,
 51         'pagesize':30
 52     }
 53     headers={                                                                            #UA伪装
 54         'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '+
 55                        'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36'
 56     }
 57     param['offset']=all_num
 58     offset = all_num                                                                           #拼接url
 59     dataRes = []
 60     findLink = re.compile(r'href="(.*?)"')  # 链接
 61     findName = re.compile(r'title="(.*?)"')  # 影片名
 62     findScore= re.compile(r'<div class="figure_score">(.*?) </div>')        #评分
 63     #3*170
 64     for i in range(0,170):
 65         # res = urllib.request.urlopen(url)                             #urllib不推荐使用
 66         res = requests.get(url=url,params=param,headers=headers)       #编辑request请求
 67         res.encoding='utf-8'                                           #设置返回数据的编码格式为utf-8
 68         html=BeautifulSoup(res.text,"html.parser")      #BeautifulSoup解析
 69         part_html = html.find_all(r"a", class_="figure")               #找到整个html界面里a标签对应的html代码,返回值是一个list
 70         offset = offset + 30                                            #修改参数字典+30部电影
 71         param['offset'] = offset
 72         print(param['offset'])
 73         for i in part_html:                                            #遍历每一个part_html
 74             # print(i)
 75             words = str(i)
 76             name=re.findall(findName, words)# 添加影片名
 77             score=re.findall(findScore, words)# 添加评分
 78             link=re.findall(findLink, words)# 添加链接
 79             findState=BeautifulSoup(words,'lxml')       #单独解析播放状态
 80             state=findState.select('a > img')           #找到img父级标签
 81             if(len(state)==1):                          #免费电影不存在播放状态的标志,所以当img长度是1的时候,需要补上一个空串
 82                 state.append("")
 83             state_text=str(state[1])                    #拿到第二个img对应的内容,使用正则匹配到alt属性对应的字符串
 84             # print(state_text)
 85             temp_state=re.findall('<img alt="(.*?)"', state_text)
 86             if(len(temp_state)==0):
 87                 temp_state.insert(0,"免费") # 添加播放状态---免费
 88             # print(temp_state[0])
 89             list_=[]
 90             if(len(score)==0):
 91                 score.insert(0,"暂无评分")
 92             for i in dataRes:
 93                 if name[0] in i[0]:
 94                     name.insert(0,name[0]+"(其他版本)")
 95             list_.append(name[0])
 96             list_.append(score[0])
 97             list_.append(link[0])
 98             list_.append(temp_state[0])
 99             # list_.append(statu)
100             # print(list_)
101             print(list_)
102             dataRes.append(list_)
103     # print(dataRes)      #打印最终结果
104     # list=html.select(".figure_score")
105     # for item in list:
106     #     print(item)
107 
108     #把同一部电影的信息放到一个 [ ] 里面
109 
110     return dataRes
111 #插入到腾讯电影数据库
112 def insert_ten():
113     """
114     插入腾讯电影数据
115     :return:
116     """
117     cursor = None
118     conn = None
119     try:
120         list = get_ten()
121         print(f"{time.asctime()}开始插入腾讯电影数据")
122         conn, cursor = get_conn()
123         sql = "insert into movieten (id,name,score,path,state) values(%s,%s,%s,%s,%s)"
124         for item in list:
125             cursor.execute(sql,[0,item[0],item[1],item[2],item[3]])
126         conn.commit()  # 提交事务 update delete insert操作
127         print(f"{time.asctime()}插入腾讯电影数据完毕")
128     except:
129         traceback.print_exc()
130     finally:
131         close_conn(conn, cursor)
132     return ;
133 if __name__ == '__main__':
134     # conn,cursor=get_conn()
135     # list=[]
136     res_list=get_ten()
137     # print(res_list)
138     # insert_ten()
原文地址:https://www.cnblogs.com/rainbow-1/p/14723538.html