一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - Python 通過xpath屬性爬取豆瓣熱映的電影信息

Python 通過xpath屬性爬取豆瓣熱映的電影信息

2022-02-28 00:15劍客阿良_ALiang Python

我喜歡看電影,可以說大部分熱門電影我都看過。處理愛好的目的,我看了看豆瓣熱映的電影列表。于是我寫了這個爬蟲把豆瓣熱映的電影都爬了下來。對頁面的處理主要是需要點擊顯示全部電影,然后爬取影片屬性,最后輸出文

前言

聲明一下:本文主要是研究使用,沒有別的用途。

GitHub倉庫地址:github項目倉庫

頁面分析

主要爬取頁面為:https://movie.douban.com/cinema/nowplaying/nanjing/

至于后面的地區,可以按照自己的需要改一下,不過多贅述了。頁面需要點擊一下展開全部影片,才能顯示全部內容,不然只有15部。所以我們使用selenium的時候,需要加一個打開頁面后的點擊邏輯。頁面圖如下:

Python 通過xpath屬性爬取豆瓣熱映的電影信息

通過F12展開的源碼,用xpath helper工具驗證一下右鍵復制下來的xpath路徑。

Python 通過xpath屬性爬取豆瓣熱映的電影信息

為了避免布局調整導致找不到,我把xpath改為通過class名獲取。

Python 通過xpath屬性爬取豆瓣熱映的電影信息

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

Python 通過xpath屬性爬取豆瓣熱映的電影信息

分析一下,是不是可以通過nowplaying的div,作為根節點,然后獲取下面class為list-item的節點,里面的屬性就是我們要的內容。

Python 通過xpath屬性爬取豆瓣熱映的電影信息

沒什么問題,那么就按照這個思路開始創建項目編碼吧。

 

實現過程

創建項目

創建一個較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()
  # 電影名
  # 電影分數
  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 通過xpath屬性爬取豆瓣熱映的電影信息

完美!!!

 

總結

最近都在寫一些爬蟲的案例,也是邊學習邊摸索,把一些實現過程記錄一下,也分享一下,等過段時間還可以回憶回憶。

分享:

情之一字,不知所起,不知所棲,不知所結,不知所解,不知所蹤,不知所終。 ――《雪中悍刀行》

如果本文對你有用的話,請不要吝嗇你的贊,謝謝!

Python 通過xpath屬性爬取豆瓣熱映的電影信息

以上就是Python 通過xpath屬性爬取豆瓣熱映的電影信息的詳細內容,更多關于Python 爬蟲豆瓣的資料請關注服務器之家其它相關文章!

原文鏈接:https://huyi-aliang.blog.csdn.net/article/details/121254579

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 男人午夜视频在线观看 | 果冻传媒mv在线观看入口免费 | a级精品九九九大片免费看 a级动漫 | 九九精品视频在线播放 | 无人区在线观看免费视频国语 | 四虎影音在线 | 黑人性xxx| 深夜在线小视频 | 高贵女王调奴vk | 我的年轻漂亮继坶三级 | 好爽轻点太大了太深了 | 男女男精品视频 | 乌克兰xxxxx 我要色色网 | 99热这里只有精品国产免费 | 亚洲欧美一区二区三区不卡 | 欧美大b| 91热国内精品永久免费观看 | 四虎国产精品免费久久麻豆 | 日韩在线视频二区 | 欧美成人momandson | 三级伦理在线播放 | caoporm碰最新免费公开视频 | 91制片厂制作果冻传媒八夷 | 美国女网址www呦女 美国复古性经典xxxxx | 按摩院已婚妇女中文字幕 | 亚洲天堂v | freexxxxxhd张柏芝 | 欧美性欲 | 日日综合 | 成人高辣h视频一区二区在线观看 | 无耻三级在线观看 | 国产成人综合一区人人 | 四虎影视在线看 | 九九艹 | 色噜噜狠狠狠综合曰曰曰88av | 国产主播99 | 久久免费观看视频 | www.久久99| 欧美日韩精品一区二区三区高清视频 | 校园全黄h全肉细节文 | 91插视频|