亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2021年11月11日 16:00:36   作者:劍客阿良_ALiang  
我喜歡看電影,可以說(shuō)大部分熱門(mén)電影我都看過(guò)。處理愛(ài)好的目的,我看了看豆瓣熱映的電影列表。于是我寫(xiě)了這個(gè)爬蟲(chóng)把豆瓣熱映的電影都爬了下來(lái)。對(duì)頁(yè)面的處理主要是需要點(diǎn)擊顯示全部電影,然后爬取影片屬性,最后輸出文本。采用的還是scrapy框架。順便聊聊我的實(shí)現(xiàn)過(guò)程吧

前言

聲明一下:本文主要是研究使用,沒(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è)面圖如下:

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

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

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

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

沒(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()
    # 電影名
    title = 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("http://*[@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)〕鏊械挠捌畔?。注意取出屬性的?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 = "http://*[@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的位置。

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

完美?。?!

總結(jié)

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

分享:

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

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

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

相關(guān)文章

  • python工具模塊介紹之time?時(shí)間訪問(wèn)和轉(zhuǎn)換的示例代碼

    python工具模塊介紹之time?時(shí)間訪問(wèn)和轉(zhuǎn)換的示例代碼

    這篇文章主要介紹了python工具模塊介紹-time?時(shí)間訪問(wèn)和轉(zhuǎn)換,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家啊的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • Python爬蟲(chóng)必備之XPath解析庫(kù)

    Python爬蟲(chóng)必備之XPath解析庫(kù)

    今天給大家?guī)?lái)的是Python爬蟲(chóng)的相關(guān)知識(shí),文章圍繞著XPath解析庫(kù)展開(kāi),文中有非常詳細(xì)的代碼示例及介紹,需要的朋友可以參考下
    2021-06-06
  • Python添加時(shí)間軸以實(shí)現(xiàn)動(dòng)態(tài)繪圖詳解

    Python添加時(shí)間軸以實(shí)現(xiàn)動(dòng)態(tài)繪圖詳解

    這篇文章主要為大家詳細(xì)介紹了Python如何添加時(shí)間軸以實(shí)現(xiàn)動(dòng)態(tài)繪圖,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以參考一下
    2023-09-09
  • 計(jì)算python腳本執(zhí)行時(shí)間的多種方法

    計(jì)算python腳本執(zhí)行時(shí)間的多種方法

    在編寫(xiě)Python腳本時(shí),了解腳本的執(zhí)行時(shí)間通常是很有用的,特別是在優(yōu)化代碼或評(píng)估性能時(shí),Python提供了多種方法來(lái)測(cè)量腳本的執(zhí)行時(shí)間,從內(nèi)置模塊到第三方庫(kù),可以選擇適合你需求的方式,本文將介紹計(jì)算 Python 腳本執(zhí)行時(shí)間的多種方法,需要的朋友可以參考下
    2023-11-11
  • Python開(kāi)發(fā)生產(chǎn)環(huán)境常用的4個(gè)工具(實(shí)用推薦)

    Python開(kāi)發(fā)生產(chǎn)環(huán)境常用的4個(gè)工具(實(shí)用推薦)

    構(gòu)建優(yōu)秀的軟件需要遵循特定的規(guī)則并執(zhí)行行業(yè)標(biāo)準(zhǔn),如何在真實(shí)的生產(chǎn)環(huán)境開(kāi)發(fā)中體現(xiàn)呢?在這篇文章中,我將向您展示我在Python項(xiàng)目中設(shè)置的4種工具,以簡(jiǎn)化開(kāi)發(fā)工作流程并執(zhí)行一些最佳實(shí)踐,這些工具幫助我提高了效率,節(jié)省了時(shí)間,希望你讀完也能有所收獲
    2024-01-01
  • python可視化爬蟲(chóng)界面之天氣查詢

    python可視化爬蟲(chóng)界面之天氣查詢

    這篇文章主要介紹了python可視化爬蟲(chóng)界面之天氣查詢的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • 在linux系統(tǒng)下安裝python librtmp包的實(shí)現(xiàn)方法

    在linux系統(tǒng)下安裝python librtmp包的實(shí)現(xiàn)方法

    今天小編就為大家分享一篇在linux系統(tǒng)下安裝python librtmp包的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07
  • python 3.7.0 安裝配置方法圖文教程

    python 3.7.0 安裝配置方法圖文教程

    這篇文章主要為大家詳細(xì)介紹了python 3.7.0 安裝配置方法圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-08-08
  • Python基礎(chǔ)知識(shí)點(diǎn) 初識(shí)Python.md

    Python基礎(chǔ)知識(shí)點(diǎn) 初識(shí)Python.md

    在本篇文章中我們給大家總結(jié)了關(guān)于Python基礎(chǔ)知識(shí)點(diǎn),通過(guò)初識(shí)Python.md的相關(guān)內(nèi)容分享給Python初學(xué)者,一起來(lái)看下吧。
    2019-05-05
  • python的flask框架難學(xué)嗎

    python的flask框架難學(xué)嗎

    在本篇內(nèi)容中小編給大家分享了關(guān)于python的flask框架是否難學(xué)的相關(guān)知識(shí)點(diǎn),有興趣的朋友們閱讀下吧。
    2020-07-07

最新評(píng)論