Python爬虫之爬取豆瓣top
Python爬虫之爬取豆瓣top
import bs4 # 网页解析,获取数据 import re # 正则表达式,进行文字匹配 import urllib.request # 制定URL,获取网页数据 import urllib.parse import xlwt # 进行Excel操作 import sqlite3 # 进行SQLite数据库操作 import time import ssl ssl._create_default_https_context = ssl._create_unverified_context def main(): baseurl = "https://movie.douban.com/top250?start=" # proxy_support = urllib.request.ProxyHandler({'http': random.choice(proxy_list)}) # askURL("https://movie.douban.com/top250?start=0") # 1.爬取网页 datalist = getData(baseurl) savepath = "豆瓣电影Top250.xls" dbpath = "movies.db" # # 3.保存数据 #saveData(datalist, savepath) saveDataDB(datalist, dbpath) # 影片信息的链接规则 findLink = re.compile(r'<a href="(.*?)">') # 创建正则表达式的对象,表示规则(字符串的模式) # 影片图片的链接规则 findImgSrc = re.compile(r'img.*src="(.*?)"', re.S) # re.S让换行符包含在字符中 # 影片的片名 findTitle = re.compile(r'<span class="title">(.*)</span>') # 影片评分 findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>') # 评价人数 findJudge = re.compile(r'<span>(\d*)人评价</span>') # 概况 findInq = re.compile(r'<span class="inq">(.*)</span>') # 影片的相关内容 findBd = re.compile(r'<p class="">(.*?)</p>', re.S) # 爬取网页 def getData(baseurl): dataList = [] for i in range(0, 10): url = baseurl + str(i * 25) html = askURL(url) # 逐一解析数据 soup = bs4.BeautifulSoup(html, "html.parser") # 以html.parser形式解析html文档 for item in soup.find_all('div', class_="item"): # 查找符合要求的字符串,形成列表 data = [] # 保存一部电影的所有信息 item = str(item) # 影片详情的链接 link = re.findall(findLink, item)[0] # re库用来通过正则表达式查找指定的字符串 data.append(link) imgSrc = re.findall(findImgSrc, item)[0] data.append(imgSrc) titles = re.findall(findTitle, item) if len(titles) == 2: ctitle = titles[0] # 添加中文名 data.append(ctitle) etitle = titles[1].replace("/", "") data.append(etitle) # 添加外名 else: data.append(titles[0]) data.append(' ') # 外名留空 rating = re.findall(findRating, item) r = rating[0] data.append(r) # 添加评分 judgeNum = re.findall(findJudge, item) j = judgeNum[0] data.append(j) # 添加评价人数 inq = re.findall(findInq,item) # 添加概述 if len(inq) != 0: inq = inq[0].replace("。", "") data.append(inq) else: data.append(" ") # 留空 bd = re.findall(findBd, item)[0] # 添加简介 bd = re.sub('<br(\s+)?/>(\s+)?', ' ', bd) data.append(bd.strip()) # bd.strip()去掉空格 dataList.append(data) # 把处理好的一部电影信息放入dataList中 return dataList # 得到指定一个URL的网页信息 def askURL(url): time.sleep(0.1) # 用户代理,表示告诉要访问的URL我们是一个什么类型的机器-浏览器(本质上是告诉浏览器我们可以接收什么水平的文件内容) # 模拟浏览器头部信息,向我们要访问的服务器发送消息 # 随机从列表中选择IP、Header head = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" } request = urllib.request.Request(url=url, headers=head) html = "" try: response = urllib.request.urlopen(request) html = response.read().decode("utf-8") except Exception as result: print(result) return html # 保存数据 def saveData(datalist, savepath): print("save……") book = xlwt.Workbook(encoding='utf-8') sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True) col = ("电影详情链接", "图片链接", "影片中文名", "影片海外名", "评分", "评价数", "概况", "相关信息") for i in range(0, 8): sheet.write(0, i, col[i]) for i in range(0, 250): print("第%d条" % (i+1)) data = datalist[i] for j in range(0, 8): sheet.write(i+1, j, data[j]) # 写入数据 book.save(savepath) # 保存 def saveDataDB(datalist, dbpath): init_db(dbpath) conn = sqlite3.connect(dbpath) cur = conn.cursor() for data in datalist: for index in range(len(data)): if index == 4 or index == 5: continue data[index] = '"'+data[index]+'"' sql = ''' insert into movie250( info_link,pic_link,cname,ename,scroe,rated,instroduction,info) values(%s)''' % (",".join(data)) cur.execute(sql) conn.commit() cur.close() conn.close() def init_db(dbpath): sql = ''' create table movie250 ( id integer primary key autoincrement, info_link text, pic_link text, cname varchar, ename varchar, scroe text, rated text, instroduction text, info text ); ''' # 创建数据表 conn = sqlite3.connect(dbpath) cursor = conn.cursor() cursor.execute(sql) conn.commit() conn.close() if __name__ == "__main__": main() # init_db('test.db') print("爬取完毕")