Python 通过xpath属性爬取豆瓣热映的电影信息

目录
  • 前言
  • 页面分析
  • 实现过程
    • 创建项目
    • Item定义
    • 中间件操作定义
    • 爬虫定义
    • 数据管道定义
    • 配置设置
    • 执行验证
  • 总结

前言

声明一下:本文主要是研究使用,没有别的用途。

GitHub仓库地址:github项目仓库

页面分析

主要爬取页面为:https://movie.douban.com/cinema/nowplaying/nanjing/

至于后面的地区,可以按照自己的需要改一下,不过多赘述了。页面需要点击一下展开全部影片,才能显示全部内容,不然只有15部。所以我们使用selenium的时候,需要加一个打开页面后的点击逻辑。页面图如下:

通过F12展开的源码,用xpath helper工具验证一下右键复制下来的xpath路径。

为了避免布局调整导致找不到,我把xpath改为通过class名获取。

然后看看每个影片的信息。

分析一下,是不是可以通过nowplaying的div,作为根节点,然后获取下面class为list-item的节点,里面的属性就是我们要的内容。

没什么问题,那么就按照这个思路开始创建项目编码吧。

实现过程

创建项目

创建一个较douban_playing的项目,使用scrapy命令。

scrapy startproject douban_playing

Item定义

定义电影信息实体。

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy

class DoubanPlayingItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    # 电影名
    title = scrapy.Field()
    # 电影分数
    score = scrapy.Field()
    # 电影发行年份
    release = scrapy.Field()
    # 电影时长
    duration = scrapy.Field()
    # 地区
    region = scrapy.Field()
    # 电影导演
    director = scrapy.Field()
    # 电影主演
    actors = scrapy.Field()

中间件操作定义

主要是点击展开全部影片,需要加一段代码。

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import time

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter
from scrapy.http import HtmlResponse
from selenium.common.exceptions import TimeoutException

class DoubanPlayingSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn't have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class DoubanPlayingDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        # return None
        try:
            spider.browser.get(request.url)
            spider.browser.maximize_window()
            time.sleep(2)
            spider.browser.find_element_by_xpath("//*[@id='nowplaying']/div[@class='more']").click()
            # ActionChains(spider.browser).click(searchButtonElement)
            time.sleep(5)
            return HtmlResponse(url=spider.browser.current_url, body=spider.browser.page_source,
                                encoding="utf-8", request=request)
        except TimeoutException as e:
            print('超时异常:{}'.format(e))
            spider.browser.execute_script('window.stop()')
        finally:
            spider.browser.close()

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

爬虫定义

按照属性名,我们取出所有的影片信息。注意取出属性的写法。

#!/user/bin/env python
# coding=utf-8
"""
@project : douban_playing
@author  : huyi
@file   : douban_playing.py
@ide    : PyCharm
@time   : 2021-11-10 16:31:23
"""

import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from douban_playing.items import DoubanPlayingItem

class DoubanPlayingSpider(scrapy.Spider):
    name = 'dbp'
    # allowed_domains = ['blog.csdn.net']
    start_urls = ['https://movie.douban.com/cinema/nowplaying/nanjing/']
    nowplaying = "//*[@id='nowplaying']/div[@class='mod-bd']//*[@class='list-item']/@{}"
    properties = ['data-title', 'data-score', 'data-release', 'data-duration', 'data-region', 'data-director',
                  'data-actors']

    def __init__(self):
        chrome_options = Options()
        chrome_options.add_argument('--headless')  # 使用无头谷歌浏览器模式
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--no-sandbox')
        self.browser = webdriver.Chrome(chrome_options=chrome_options,
                                        executable_path="E:\\chromedriver_win32\\chromedriver.exe")
        self.browser.set_page_load_timeout(30)

    def parse(self, response, **kwargs):
        titles = response.xpath(self.nowplaying.format(self.properties[0])).extract()
        scores = response.xpath(self.nowplaying.format(self.properties[1])).extract()
        releases = response.xpath(self.nowplaying.format(self.properties[2])).extract()
        durations = response.xpath(self.nowplaying.format(self.properties[3])).extract()
        regions = response.xpath(self.nowplaying.format(self.properties[4])).extract()
        directors = response.xpath(self.nowplaying.format(self.properties[5])).extract()
        actors = response.xpath(self.nowplaying.format(self.properties[6])).extract()
        for x in range(len(titles)):
            item = DoubanPlayingItem()
            item['title'] = titles[x]
            item['score'] = scores[x]
            item['release'] = releases[x]
            item['duration'] = durations[x]
            item['region'] = regions[x]
            item['director'] = directors[x]
            item['actors'] = actors[x]
            yield item

数据管道定义

还是老样子,把取出的电影数据按照格式输出在文本中。

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

class DoubanPlayingPipeline:
    def __init__(self):
        self.file = open('result.txt', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        self.file.write(
            "电影:{}\t分数:{}\t发行年份:{}\t电影时长:{}\t地区:{}\t电影导演:{}\t电影主演:{}\n".format(
                item['title'],
                item['score'],
                item['release'],
                item['duration'],
                item['region'],
                item['director'],
                item['actors']))
        return item

    def close_spider(self, spider):
        self.file.close()

配置设置

都是一些常规的,放开几个默认配置就行。

# Scrapy settings for douban_playing project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'douban_playing'

SPIDER_MODULES = ['douban_playing.spiders']
NEWSPIDER_MODULE = 'douban_playing.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'douban_playing (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36'
}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
SPIDER_MIDDLEWARES = {
   'douban_playing.middlewares.DoubanPlayingSpiderMiddleware': 543,
}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'douban_playing.middlewares.DoubanPlayingDownloaderMiddleware': 543,
}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'douban_playing.pipelines.DoubanPlayingPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

执行验证

还是老样子,不直接使用scrapy命令,构造一个py执行cmd。注意该py的位置。

看一下执行后的结果。

完美!!!

总结

最近都在写一些爬虫的案例,也是边学习边摸索,把一些实现过程记录一下,也分享一下,等过段时间还可以回忆回忆。

分享:

情之一字,不知所起,不知所栖,不知所结,不知所解,不知所踪,不知所终。 ——《雪中悍刀行》

如果本文对你有用的话,请不要吝啬你的赞,谢谢!

以上就是Python 通过xpath属性爬取豆瓣热映的电影信息的详细内容,更多关于Python 爬虫豆瓣的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python爬取你好李焕英豆瓣短评生成词云的示例代码

    爬取过程: 你好,李焕英 短评的URL: https://movie.douban.com/subject/34841067/comments?start=20&limit=20&status=P&sort=new_score 分析要爬取的URL; 34841067:电影ID start=20:开始页面 limit=20:每页评论条数 代码: url = 'https://movie.douban.com/subject/%s/comments?start=%s&limit

  • 使用Python编程分析火爆全网的鱿鱼游戏豆瓣影评

    目录 技术工具 数据采集 数据可视化 垂直布局 水平布局 词云可视化 小结 Hello,各位读者朋友们好啊,我是小张~ 这不国庆嘛,就把最近很火的一个韩剧<鱿鱼游戏>刷了下,这部剧整体剧情来说还是非常不错的,很值得一看, 作为一个技术博主,当然不能在这儿介绍这部剧的影评,毕竟自己在这方面不是专业的,最关键还是自己也写不出来 技术工具 在正文开始之前,先介绍下本篇文章中用到的技术栈和工具. 本文用到的技术栈和工具如下,归结为四个方面: 语言:Python,Vue ,javascript: 存储:

  • python 爬取豆瓣网页的示例

    python作为一种已经广泛传播且相对易学的解释型语言,现如今在各方面都有着广泛的应用.而爬虫则是其最为我们耳熟能详的应用,今天笔者就着重针对这一方面进行介绍. python 语法简要介绍 python 的基础语法大体与c语言相差不大,由于省去了c语言中的指针等较复杂的结构,所以python更被戏称为最适合初学者的语言.而在基础语法之外,python由其庞大的第三方库组成,而其中包含多种模块,而通过模块中包含的各种函数与方法能够帮助我们实现各种各样的功能. 而在python爬虫中,我们需要用到的

  • python爬取豆瓣电影排行榜(requests)的示例代码

    '''   爬取豆瓣电影排行榜   设计思路:        1.先获取电影类型的名字以及特有的编号        2.将编号向ajax发送get请求获取想要的数据        3.将数据存放进excel表格中 ''' 环境部署: 软件安装: Python 3.7.6 官网地址:https://www.python.org/ 安装地址:https://www.python.org/ftp/python/3.7.6/python-3.7.6-amd64.exe PyCharm 2020.2.2

  • python爬取豆瓣电影TOP250数据

    在执行程序前,先在MySQL中创建一个数据库"pachong". import pymysql import requests import re #获取资源并下载 def resp(listURL): #连接数据库 conn = pymysql.connect( host = '127.0.0.1', port = 3306, user = 'root', password = '******', #数据库密码请根据自身实际密码输入 database = 'pachong', cha

  • Python爬虫实战之使用Scrapy爬取豆瓣图片

    使用Scrapy爬取豆瓣某影星的所有个人图片 以莫妮卡·贝鲁奇为例 1.首先我们在命令行进入到我们要创建的目录,输入 scrapy startproject banciyuan 创建scrapy项目 创建的项目结构如下 2.为了方便使用pycharm执行scrapy项目,新建main.py from scrapy import cmdline cmdline.execute("scrapy crawl banciyuan".split()) 再edit configuration 然后

  • 详解如何用Python登录豆瓣并爬取影评

    目录 一.需求背景 二.功能描述 三.技术方案 四.登录豆瓣 1.分析豆瓣登录接口 2.代码实现登录豆瓣 3.保存会话状态 4.这个Session对象是我们常说的session吗? 五.爬取影评 1.分析豆瓣影评接口 2.爬取一条影评数据 3.影评内容提取 4.批量爬取 六.分析影评 1.使用结巴分词 七.总结 上一篇我们讲过Cookie相关的知识,了解到Cookie是为了交互式web而诞生的,它主要用于以下三个方面: 会话状态管理(如用户登录状态.购物车.游戏分数或其它需要记录的信息) 个性化

  • Python爬取豆瓣数据实现过程解析

    代码如下 from bs4 import BeautifulSoup #网页解析,获取数据 import sys #正则表达式,进行文字匹配 import re import urllib.request,urllib.error #指定url,获取网页数据 import xlwt #使用表格 import sqlite3 import lxml 以上是引用的库,引用库的方法很简单,直接上图: 上面第一步算有了,下面分模块来,步骤算第二步来: 这个放在开头 def main(): baseurl

  • Python 通过xpath属性爬取豆瓣热映的电影信息

    目录 前言 页面分析 实现过程 创建项目 Item定义 中间件操作定义 爬虫定义 数据管道定义 配置设置 执行验证 总结 前言 声明一下:本文主要是研究使用,没有别的用途. GitHub仓库地址:github项目仓库 页面分析 主要爬取页面为:https://movie.douban.com/cinema/nowplaying/nanjing/ 至于后面的地区,可以按照自己的需要改一下,不过多赘述了.页面需要点击一下展开全部影片,才能显示全部内容,不然只有15部.所以我们使用selenium的时

  • Python利用Scrapy框架爬取豆瓣电影示例

    本文实例讲述了Python利用Scrapy框架爬取豆瓣电影.分享给大家供大家参考,具体如下: 1.概念 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. 通过Python包管理工具可以很便捷地对scrapy进行安装,如果在安装中报错提示缺少依赖的包,那就通过pip安装所缺的包 pip install scrapy scrapy的组成结构如下图所示 引擎Scrapy Engine,用于中转调度其他部分的信号和数据

  • Python网络爬虫之爬取微博热搜

    微博热搜的爬取较为简单,我只是用了lxml和requests两个库 url= https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6 1.分析网页的源代码:右键--查看网页源代码. 从网页代码中可以获取到信息 (1)热搜的名字都在<td class="td-02">的子节点<a>里 (2)热搜的排名都在<td class=td-01 ranktop>的里(注意置顶微博是

  • python使用re模块爬取豆瓣Top250电影

    爬蟲四步原理: 1.发送请求:requests 2.获取相应数据:对方及其直接返回 3.解析并提取想要的数据:re 4.保存提取后的数据:with open()文件处理 爬蟲三步曲: 1.发送请求 2.解析数据 3.保存数据 注意:豆瓣网页爬虫必须使用请求头,否则服务器不予返回数据 import re import requests # 爬蟲三部曲: # 1.获取请求 def get_data(url, headers): response = requests.get(url, headers

  • Python趣味爬虫之爬取爱奇艺热门电影

    一.首先我们要找到目标 找到目标先分析一下网页很幸运这个只有一个网页,不需要翻页. 二.F12查看网页源代码 找到目标,分析如何获取需要的数据.找到href与电影名称 三.进行代码实现,获取想要资源. ''' 操作步骤 1,获取到url内容 2,css选择其选择内容 3,保存自己需要数据 ''' #导入爬虫需要的包 import requests from bs4 import BeautifulSoup #requests与BeautifulSoup用来解析网页的 import time #设

  • Python使用Beautiful Soup爬取豆瓣音乐排行榜过程解析

    前言 要想学好爬虫,必须把基础打扎实,之前发布了两篇文章,分别是使用XPATH和requests爬取网页,今天的文章是学习Beautiful Soup并通过一个例子来实现如何使用Beautiful Soup爬取网页. 什么是Beautiful Soup Beautiful Soup是一款高效的Python网页解析分析工具,可以用于解析HTL和XML文件并从中提取数据. Beautiful Soup输入文件的默认编码是Unicode,输出文件的编码是UTF-8. Beautiful Soup具有将

  • Python利用lxml模块爬取豆瓣读书排行榜的方法与分析

    前言 上次使用了BeautifulSoup库爬取电影排行榜,爬取相对来说有点麻烦,爬取的速度也较慢.本次使用的lxml库,我个人是最喜欢的,爬取的语法很简单,爬取速度也快. 本次爬取的豆瓣书籍排行榜的首页地址是: https://www.douban.com/doulist/1264675/?start=0&sort=time&playable=0&sub_type= 该排行榜一共有22页,且发现更改网址的 start=0 的 0 为25.50就可以跳到排行榜的第二.第三页,所以后

  • Python使用mongodb保存爬取豆瓣电影的数据过程解析

    创建爬虫项目douban scrapy startproject douban 设置items.py文件,存储要保存的数据类型和字段名称 # -*- coding: utf-8 -*- import scrapy class DoubanItem(scrapy.Item): title = scrapy.Field() # 内容 content = scrapy.Field() # 评分 rating_num = scrapy.Field() # 简介 quote = scrapy.Field(

  • Python利用Xpath选择器爬取京东网商品信息

    HTML文件其实就是由一组尖括号构成的标签组织起来的,每一对尖括号形式一个标签,标签之间存在上下关系,形成标签树:XPath 使用路径表达式在 XML 文档中选取节点.节点是通过沿着路径或者 step 来选取的. 首先进入京东网,输入自己想要查询的商品,向服务器发送网页请求.在这里小编仍以关键词"狗粮"作为搜索对象,之后得到后面这一串网址: https://search.jd.com/Search?keyword=%E7%8B%97%E7%B2%AE&enc=utf-8,其中参

  • python爬取豆瓣评论制作词云代码

    目录 一.爬取豆瓣热评 二.制作词云 总结 一.爬取豆瓣热评 该程序进行爬取豆瓣热评,将爬取的评论(json文件)保存到与该python文件同一级目录下注意需要下载这几个库:requests.lxml.json.time import requests from lxml import etree import json import time class Spider(object): def __init__(self): #seif.ure='https://movie.douban.co

随机推荐