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

腳本之家,腳本語(yǔ)言編程技術(shù)及教程分享平臺(tái)!
分類(lèi)導(dǎo)航

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

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

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

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

我喜歡看電影,可以說(shuō)大部分熱門(mén)電影我都看過(guò)。處理愛(ài)好的目的,我看了看豆瓣熱映的電影列表。于是我寫(xiě)了這個(gè)爬蟲(chóng)把豆瓣熱映的電影都爬了下來(lái)。對(duì)頁(yè)面的處理主要是需要點(diǎn)擊顯示全部電影,然后爬取影片屬性,最后輸出文

前言

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

GitHub倉(cāng)庫(kù)地址:github項(xiàng)目倉(cāng)庫(kù)

頁(yè)面分析

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

至于后面的地區(qū),可以按照自己的需要改一下,不過(guò)多贅述了。頁(yè)面需要點(diǎn)擊一下展開(kāi)全部影片,才能顯示全部?jī)?nèi)容,不然只有15部。所以我們使用selenium的時(shí)候,需要加一個(gè)打開(kāi)頁(yè)面后的點(diǎn)擊邏輯。頁(yè)面圖如下:

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

通過(guò)F12展開(kāi)的源碼,用xpath helper工具驗(yàn)證一下右鍵復(fù)制下來(lái)的xpath路徑。

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

為了避免布局調(diào)整導(dǎo)致找不到,我把xpath改為通過(guò)class名獲取。

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

然后看看每個(gè)影片的信息。

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

分析一下,是不是可以通過(guò)nowplaying的div,作為根節(jié)點(diǎn),然后獲取下面class為list-item的節(jié)點(diǎn),里面的屬性就是我們要的內(nèi)容。

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

沒(méi)什么問(wèn)題,那么就按照這個(gè)思路開(kāi)始創(chuàng)建項(xiàng)目編碼吧。

 

實(shí)現(xiàn)過(guò)程

創(chuàng)建項(xiàng)目

創(chuàng)建一個(gè)較douban_playing的項(xiàng)目,使用scrapy命令。

scrapy startproject douban_playing

Item定義

定義電影信息實(shí)體。

# 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()
  # 電影名
  # 電影分?jǐn)?shù)
  score = scrapy.Field()
  # 電影發(fā)行年份
  release = scrapy.Field()
  # 電影時(shí)長(zhǎng)
  duration = scrapy.Field()
  # 地區(qū)
  region = scrapy.Field()
  # 電影導(dǎo)演
  director = scrapy.Field()
  # 電影主演
  actors = scrapy.Field()

中間件操作定義

主要是點(diǎn)擊展開(kāi)全部影片,需要加一段代碼。

# 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('超時(shí)異常:{}'.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)

爬蟲(chóng)定義

按照屬性名,我們?nèi)〕鏊械挠捌畔ⅰW⒁馊〕鰧傩缘膶?xiě)法。

#!/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')  # 使用無(wú)頭谷歌瀏覽器模式
      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

數(shù)據(jù)管道定義

還是老樣子,把取出的電影數(shù)據(jù)按照格式輸出在文本中。

# 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分?jǐn)?shù):{}\t發(fā)行年份:{}\t電影時(shí)長(zhǎng):{}\t地區(qū):{}\t電影導(dǎo)演:{}\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()

配置設(shè)置

都是一些常規(guī)的,放開(kāi)幾個(gè)默認(rèn)配置就行。

# 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'

執(zhí)行驗(yàn)證

還是老樣子,不直接使用scrapy命令,構(gòu)造一個(gè)py執(zhí)行cmd。注意該py的位置。

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

看一下執(zhí)行后的結(jié)果。

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

完美!!!

 

總結(jié)

最近都在寫(xiě)一些爬蟲(chóng)的案例,也是邊學(xué)習(xí)邊摸索,把一些實(shí)現(xiàn)過(guò)程記錄一下,也分享一下,等過(guò)段時(shí)間還可以回憶回憶。

分享:

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

如果本文對(duì)你有用的話,請(qǐng)不要吝嗇你的贊,謝謝!

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

以上就是Python 通過(guò)xpath屬性爬取豆瓣熱映的電影信息的詳細(xì)內(nèi)容,更多關(guān)于Python 爬蟲(chóng)豆瓣的資料請(qǐng)關(guān)注服務(wù)器之家其它相關(guān)文章!

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 人妖欧美一区二区三区四区 | 极品美女aⅴ高清在线观看 极品ts赵恩静和直男激战啪啪 | 亚洲香蕉伊在人在线观看9 亚洲系列国产系列 | 日本高清视频一区二区 | 无码毛片内射白浆视频 | 午夜毛片在线观看 | 我和么公的秘密小说免费 | 26uuu久久| 色久激情| 天天做日日做天天添天天欢公交车 | 欧美成人另类人妖 | 久久国产伦子伦精品 | 十大免费批日的软件 | 加勒比一本大道香蕉在线视频 | 日b视频免费看 | 性绞姿始动作动态图 | 猛男深夜狂cao小男生 | 小柔的性放荡羞辱日记 | 暖暖视频高清图片免费完整版 | 草馏社区最新1024 | 精品久久久久亚洲 | 奇米影视先锋 | 国产草草视频 | 秋霞黄色网 | 双性总裁(h) | 十八女下面流水不遮免费 | 国产自拍专区 | 欧美成人午夜片一一在线观看 | 好姑娘在线视频观看免费 | 欧美男人天堂 | 亚洲国产综合另类视频 | 精品国产人成亚洲区 | 私人黄色 | 亚洲日本免费 | 肉浦团在线观看 | 国产精品青青青高清在线观看 | 日韩在线观看一区二区不卡视频 | 变态 调教 视频 国产九色 | 黑人巨茎大战欧美白妇 | 欧美添下面视频免费观看 | 国产精品边做边接电话在线观看 |