Python爬取豆瓣电影Top250(正则表达式)

与豆瓣读书相似,规则设置部分有些不同
此处代码参考B站李巍老师讲解的爬虫

# -*- coding = utf-8 -*-

from bs4 import  BeautifulSoup #网页解析,获取数据
import re   #正则表达式,进行文字匹配
import urllib.request, urllib.error #制定URL,获取网页数据
import xlwt #进行excel操作
import sqlite3 #进行SQLit操作
def main():
    baseurl = "https://movie.douban.com/top250?start="
    #1、爬取网页
    datalist = getData(baseurl)
    #2、解析数据
    # savepath = "‪C:\Users\J\Desktop\Save.xls"
    savepath = "C:\\Users\\J\\Desktop\\Save1.xls"
    saveData(datalist,savepath)

    askURL("https://movie.douban.com/top250?start=")
    #3、保存数据
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)
        #2.逐一解析数据
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all('div',class_="item" ):
            data = []#保存一部电影的所有信息
            item = str(item)

        #影片详情的链接
            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)[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

def askURL(url):
    #模拟浏览器头部信息,向豆瓣服务器发送消息
    head={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}
    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爬取豆瓣电影Top250(正则表达式)_第1张图片

你可能感兴趣的:(Python爬取豆瓣电影Top250(正则表达式))