最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)文章

最新評(píng)論

乐亭县| 清水河县| 琼结县| 都兰县| 苗栗县| 阳山县| 河北区| 宝坻区| 阳西县| 洪江市| 彭水| 浑源县| 南郑县| 镇巴县| 泗洪县| 辽中县| 双江| 罗江县| 淮安市| 日土县| 烟台市| 吉林省| 吴旗县| 丰县| 宾川县| 怀来县| 偃师市| 安远县| 辽阳县| 闽侯县| 旬邑县| 安阳县| 长阳| 资兴市| 抚州市| 信丰县| 郁南县| 吉木萨尔县| 昌宁县| 英山县| 察哈|