Python爬虫豆瓣T250电影

# -*- codeing = utf-8 -*-
from bs4 import BeautifulSoup
import re
import urllib.request,urllib.error
import xlwt


def main():
    baseurl = "https://movie.douban.com/top250?start=0"
    #爬取网页
    datalist = getData(baseurl)
    savepath = ".\\豆瓣电影Top250.xls"
    # 保存数据
    saveData(datalist,savepath)
    #askURL("https://movie.douban.com/top250?start=0")

findLink = re.compile(r'')     #生成正则表达式对象
findImgSrc = re.compile(r'(.*)') #片名
findRating = re.compile(r'(.*)')   #评分
findJudge = re.compile(r'(\d*)人评价')        #评价人数
findInq = re.compile(r'(.*)')  #概况
findBd = re.compile(r'

(.*?)

',re.S) #爬取网页 def getData(baseurl): datalist = [] for i in range(0,10): #调用获取页面信息函数 url = baseurl + str(i*25) html = askURL(url) #保存获取网页源码 # 解析数据 soup = BeautifulSoup(html,"html.parser") 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) otitle = titles[1].replace("/","") #替换/ data.append(otitle) else: data.append(titles[0]) data.append('') #外国名留空 rating = re.findall(findRating,item)[0] data.append(rating) #评分 judgeNum = re.findall(findJudge,item)[0] data.append(judgeNum) #评价人数 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('(\s+)?'," ",bd) #去掉
bd = re.sub('/'," ",bd) #替换/ data.append(bd.strip()) #去掉空格 datalist.append(data) return datalist #得到一个指定URL网页 def askURL(url): # 模拟浏览器头部信息 head = { "User-Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 94.0.4606.81Safari / 537.36Edg / 94.0.992.50" } #伪装浏览器 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 #保存数据 def saveData(datalist,savepath): print("save...") book = xlwt.Workbook(encoding="utf-8",style_compression=0) 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) if __name__=="__main__": #当程序执行时 #调用函数 main() print("爬取完毕!")

你可能感兴趣的:(python,爬虫,开发语言)