python爬取豆瓣电影TOP250信息

# -*- coding:utf-8 -*-
import urllib.request
import jsonpath
import json
import re # 正则表达式
import xlwt # 进行excel操作
import sqlite3 # 进行SQLite数据库操作
from bs4 import BeautifulSoup # 网页解析,获取数据


# 需要的访问内容,创建增则表达式对象
findLink = re.compile(r'')  # 网页链接
findImgSrc = re.compile(r', re.S)  # 图片,re.S是让换行符包含在字符中
findTitle = re.compile(r'(.*?)')  # 片名
findRating = re.compile(r'(.*?)')  # 评分
findJudge = re.compile(r'(\d*)人评价')  # 评分人数
findInq = re.compile(r'(.*?)')  # 找概况
findBd = re.compile(r'

(.*?)

'
, re.S) # 相关内容 # 爬虫爬取豆瓣前250电影信息 def main(): baseurl = "https://movie.douban.com/top250?start=" # 1.爬取网页 datalist = getData(baseurl) # 3.保存数据 savepath = ".\\豆瓣电影Top.xls" saveData(datalist,savepath) print("爬取完毕") # 1.爬取网页 def getData(baseurl): datalist = [] for i in range(0, 250, 25): url = baseurl + str(i) html = askURL(url) # 2.解析数据 soup = BeautifulSoup(html, "html.parser") for item in soup.find_all('div', class_="item"): data = [] # 保存这个电影所有信息 item = str(item) # re通过正则表达式找链接 link = re.findall(findLink, item)[0] 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) otitle = titles[1].replace("/", "") # 外文名,去掉斜杠 data.append(otitle) else: data.append(titles[0]) data.append("") # 留空,保证数据对齐 # 打分 rating = re.findall(findRating, item) data.append(rating) # 评价人数 judgeNum = re.findall(findJudge, item) data.append(judgeNum) # 概述 inq = re.findall(findInq,item) if len(inq)!=0: inq = inq[0].replace("。","") else: inq = " " # 留空,保证数据对齐 data.append(inq) # 相关内容 bd = re.findall(findBd,item)[0] bd = re.sub('(\s+)?'," ",bd) # 去掉
bd = re.sub('/'," ",bd) # 去掉 / data.append(bd.strip()) # 去掉空格 datalist.append(data) return datalist # 3.保存数据 def saveData(datalist,savepath): book = xlwt.Workbook(encoding="utf-8",style_compression=0) sheet = book.add_sheet('豆瓣电影Top250',cell_overwrite_ok=True) col = ("电影详情链接","图片","中文名","外文名","评分","评价数","概况","相关信息") for i in range(8): sheet.write(0,i,col[i]) for i in range(len(datalist)): print("第%d条"%i) data = datalist[i] for j in range(len(data)): sheet.write(i+1,j,data[j]) book.save(savepath) # 访问URL def askURL(url): head = { "User-Agent": "Mozilla/5.0(Windows NT 10.0;Win64;x64)AppleWebKit/537.36(KHTML,like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18363" } request = urllib.request.Request(url, headers=head) html = "" try: response = urllib.request.urlopen(request) html = response.read().decode("utf-8") # print(html) except urllib.error.URLError as e: if hasattr(e, "code"): print(e, code) if hasattr(e, "reason"): print(e, reason) return html if __name__ == "__main__": main()

你可能感兴趣的:(Python,杂记,python,正则表达式)