自学Python爬虫的手写代码

自学Python爬虫的手写代码

from bs4 import BeautifulSoup
import re  # 正则表达式, 进行文字匹配
import urllib.request, urllib.error  # 制定URL, 获取网页数据
import xlwt  # 进行Excel操作
import sqlite3  # 进行SQLite数据库操作

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

        # 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]  # 用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("/", "")  # 添加外国名
                otitle = str(otitle).replace(u'\xa0', '')
                # otitle = otitle.replace('&nbsp'," ")
                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('<br(\s+)?/>(\s+)?', " ", bd)  # 去掉<br/>
            bd = re.sub('/', " ", bd)  # 替换空格
            bd =str(bd).replace(u'\xa0'," ")
            bd = bd.strip()  # 去掉前后空格
            data.append(bd)

            dataList.append(data)  # 把处理好的一部电影的信息放入dataList
    # print(dataList)  # 打印所有的内容
    return dataList


# 保存数据
def SaveData(savePath, dataList):
    workbook = xlwt.Workbook(encoding="utf-8", style_compression=0)
    worksheet = workbook.add_sheet("豆瓣电影Top250", cell_overwrite_ok=True)
    col = ("电影详情链接", "图片链接", "影片中文名", "影片外国名", "评分", "评价数", "概况", "相关信息")
    for i in range(0, 8):
        worksheet.write(0, 1, col[i])

    for i in range(0, 250):
        print("第%d条" % (i + 1))
        data = dataList[i]
        for j in range(0, 8):
            worksheet.write(i + 1, j, data[j])
    workbook.save(savePath)  # 保存


def SaveDataDB(dataList, dbpath):
    Init_db(dbpath)
    con = sqlite3.connect(dbpath)
    cursor = con.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,score,rated,introduction,info)
            values(%s)''' % ",".join(data)
        # print(sql)
        cursor.execute(sql)
        con.commit()
    cursor.close()
    con.close()


def Init_db(dbpath):
    sql = '''
        create table if not exists movie250
        (
        id integer primary key autoincrement,
        info_link text,
        pic_link text,
        cname varchar,
        ename varchar,
        score numeric,
        rated numeric,
        introduction text,
        info text
        )
    '''
    con = sqlite3.connect(dbpath)
    cursor = con.cursor()
    cursor.execute(sql)
    con.commit()
    con.close()


# 获得特定一个URL的网页内容
def AskURL(URL):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36 Edg/103.0.1264.44"
    }
    request = urllib.request.Request(url=URL, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
        # print(html)
    except Exception as e:
        if hasattr(e, "code"):
            print(e.code)
        elif hasattr(e, "reason"):
            print(e.reason)
    return html


def main():
    baseURL = "https://movie.douban.com/top250?start=0"
    dataList = GetData(baseURL)
    dbpath = "movie.db"
    SaveDataDB(dataList, dbpath)
    # savePath = ".\\豆瓣电影Top250.xls"
    # SaveData(savePath, dataList)


if __name__ == "__main__":
    main()
    print("爬取完毕")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值