【python】爬取豆瓣电影排行榜TOP250存储到CSV文件中【附源码】

 一、导入必要的模块:

       代码首先导入了需要使用的模块:requests、lxml和csv。

import requests
from lxml import etree
import csv

        如果出现模块报错

        进入控制台输入:建议使用国内镜像源

pip install 模块名称 -i https://mirrors.aliyun.com/pypi/simple

         我大致罗列了以下几种国内镜像源:

清华大学
https://pypi.tuna.tsinghua.edu.cn/simple

阿里云
https://mirrors.aliyun.com/pypi/simple/

豆瓣
https://pypi.douban.com/simple/ 

百度云
https://mirror.baidu.com/pypi/simple/

中科大
https://pypi.mirrors.ustc.edu.cn/simple/

华为云
https://mirrors.huaweicloud.com/repository/pypi/simple/

腾讯云
https://mirrors.cloud.tencent.com/pypi/simple/

    

二、定义了函数来解析每个电影的信息:

        设置了请求头部信息,以模拟浏览器的请求,函数返回响应数据的JSON格式内容。

def getSource(url):
    # 反爬 填写headers请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
    }

    response = requests.get(url, headers=headers)
    # 防止出现乱码
    response.encoding = 'utf-8'
    # print(response.text)
    return response.text

        如何获取请求头:

        火狐浏览器:
  1. 打开目标网页并右键点击页面空白处。
  2. 选择“检查元素”选项,或按下快捷键Ctrl + Shift + C(Windows)
  3. 在开发者工具窗口中,切换到“网络”选项卡。
  4. 刷新页面以捕获所有的网络请求。
  5. 在请求列表中选择您感兴趣的请求。
  6. 在右侧的“请求标头”或“Request Headers”部分,即可找到请求头信息。

     将以下请求头信息复制出来即可

三、定义了函数将电影信息写入CSV文件

        使用csv库的DictWriter类,创建一个CSV写入对象,并指定列名为"title"、"star"、"quote"和"url"。然后,逐行写入电影信息到CSV文件中。

def getEveryItem(source):
    html_element = etree.HTML(source)

    movieItemList = html_element.xpath('//div[@class="info"]')

    # 定义一个空的列表
    movieList = []

    for eachMoive in movieItemList:

        # 创建一个字典 像列表中存储数据[{电影一},{电影二}......]
        movieDict = {}

        title = eachMoive.xpath('div[@class="hd"]/a/span[@class="title"]/text()')  # 标题
        otherTitle = eachMoive.xpath('div[@class="hd"]/a/span[@class="other"]/text()')  # 副标题
        link = eachMoive.xpath('div[@class="hd"]/a/@href')[0]  # url
        star = eachMoive.xpath('div[@class="bd"]/div[@class="star"]/span[@class="rating_num"]/text()')[0]  # 评分
        quote = eachMoive.xpath('div[@class="bd"]/p[@class="quote"]/span/text()')  # 引言(名句)

        if quote:
            quote = quote[0]
        else:
            quote = ''
        # 保存数据
        movieDict['title'] = ''.join(title + otherTitle)
        movieDict['url'] = link
        movieDict['star'] = star
        movieDict['quote'] = quote

        movieList.append(movieDict)

        print(movieList)
    return movieList

四、源码:


#代码首先导入了需要使用的模块:requests、lxml和csv。
import requests
from lxml import etree
import csv

#
doubanUrl = 'https://movie.douban.com/top250?start={}&filter='


# 然后定义了豆瓣电影TOP250页面的URL地址,并实现了一个函数getSource(url)来获取网页的源码。该函数发送HTTP请求,添加了请求头信息以防止被网站识别为爬虫,并通过requests.get()方法获取网页源码。
def getSource(url):
    # 反爬 填写headers请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
    }

    response = requests.get(url, headers=headers)
    # 防止出现乱码
    response.encoding = 'utf-8'
    # print(response.text)
    return response.text


# 定义了一个函数getEveryItem(source)来解析每个电影的信息。首先,使用lxml库的etree模块将源码转换为HTML元素对象。然后,使用XPath表达式定位到包含电影信息的每个HTML元素。通过对每个元素进行XPath查询,提取出电影的标题、副标题、URL、评分和引言等信息。最后,将这些信息存储在一个字典中,并将所有电影的字典存储在一个列表中。
def getEveryItem(source):
    html_element = etree.HTML(source)

    movieItemList = html_element.xpath('//div[@class="info"]')

    # 定义一个空的列表
    movieList = []

    for eachMoive in movieItemList:

        # 创建一个字典 像列表中存储数据[{电影一},{电影二}......]
        movieDict = {}

        title = eachMoive.xpath('div[@class="hd"]/a/span[@class="title"]/text()')  # 标题
        otherTitle = eachMoive.xpath('div[@class="hd"]/a/span[@class="other"]/text()')  # 副标题
        link = eachMoive.xpath('div[@class="hd"]/a/@href')[0]  # url
        star = eachMoive.xpath('div[@class="bd"]/div[@class="star"]/span[@class="rating_num"]/text()')[0]  # 评分
        quote = eachMoive.xpath('div[@class="bd"]/p[@class="quote"]/span/text()')  # 引言(名句)

        if quote:
            quote = quote[0]
        else:
            quote = ''
        # 保存数据
        movieDict['title'] = ''.join(title + otherTitle)
        movieDict['url'] = link
        movieDict['star'] = star
        movieDict['quote'] = quote

        movieList.append(movieDict)

        print(movieList)
    return movieList


# 保存数据
def writeData(movieList):
    with open('douban.csv', 'w', encoding='utf-8', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=['title', 'star', 'quote', 'url'])

        writer.writeheader()  # 写入表头

        for each in movieList:
            writer.writerow(each)


if __name__ == '__main__':
    movieList = []

    # 一共有10页

    for i in range(10):
        pageLink = doubanUrl.format(i * 25)

        source = getSource(pageLink)

        movieList += getEveryItem(source)

    writeData(movieList)

        首先,我们导入了需要用到的三个Python模块:requests、lxml和csv。

        然后,我们定义了豆瓣电影TOP250页面的URL地址,并使用getSource(url)函数获取网页源码。

        接着,我们定义了一个getEveryItem(source)函数,它使用XPath表达式从HTML源码中提取出每部电影的标题、URL、评分和引言,并将这些信息存储到一个字典中,最后将所有电影的字典存储到一个列表中并返回。

        然后,我们定义了一个writeData(movieList)函数,它使用csv库的DictWriter类创建一个CSV写入对象,然后将电影信息列表逐行写入CSV文件。

        最后,在if __name__ == '__main__'语句块中,我们定义了一个空的电影信息列表movieList,然后循环遍历前10页豆瓣电影TOP250页面,分别抓取每一页的网页源码,并使用getEveryItem()函数解析出电影信息并存储到movieList中,最后使用writeData()函数将电影信息写入CSV文件。

五、效果图:

 给大家推荐一个网站

    IT今日热榜 一站式资讯平台


        里面包含了上百个IT网站,欢迎大家访问:IT今日热榜 一站式资讯平台

   iToday,打开信息的新时代。作为一家创新的IT数字媒体平台,iToday致力于为用户提供最新、最全面的IT资讯和内容。里面包含了技术资讯、IT社区、面试求职、前沿科技等诸多内容。我们的团队由一群热爱创作的开发者和分享的专业编程知识爱好者组成,他们精选并整理出真实可信的信息,确保您获得独特、有价值的阅读体验。随时随地,尽在iToday,与世界保持连接,开启您的信息新旅程!IT今日热榜 一站式资讯平台IT今日热榜汇聚各类IT热榜:虎嗅、知乎、36氪、京东图书销售、晚点、全天候科技、极客公园、GitHub、掘金、CSDN、哔哩哔哩、51CTO、博客园、GitChat、开发者头条、思否、LeetCode、人人都是产品经理、牛客网、看准、拉勾、Boss直聘icon-default.png?t=N7T8http://itoday.top/#/

猜你喜欢

转载自blog.csdn.net/m0_73367097/article/details/134121460