本文分享Python如何通过xpath属性抓取豆瓣热门电影的信息。边肖觉得很实用,所以分享给大家学习。希望你看完这篇文章能有所收获。让我们和边肖一起看看。
前言
备案:本文主要用于研究,无其他用途。
github仓库地址:GitHub项目仓库
页面分析
主爬行页面是:https://movie.douban.com/cinema/nowplaying/nanjing/.
至于后面几个方面,你可以根据自己的需要进行更改,但我会详细介绍。你需要点击页面展开所有电影才能显示所有内容,否则只有15部电影。所以我们在使用selenium的时候,需要在打开页面之后添加一个点击逻辑。页面如下:
通过F12源代码,使用xpath助手工具验证右击复制的xpath路径。
为了避免因为布局调整而被发现,我把xpath改成了按类名取。
然后看每部电影的信息。
分析是否可以用nowplaying的div作为根节点,然后用class list-item得到下面的节点,里面的属性就是我们想要的。
没问题,那就按照这个思路开始创建项目代码。
00-101010
实现过程
创建一个比豆瓣_playing更大的项目,并使用scrapy命令。
scrapy startproject豆瓣_播放
创建项目
定义电影信息实体。
# defineherethemodelsforursleditems
#
#种子文档:
# https://docs . scrapy . org/en/latest/topics/items . html
进口废料
classDoubanPlayingItem(剪贴簿。项目):
# definethefieldsforyourtemherelike :
#name=scrapy。字段()
#电影标题
标题=剪贴簿。字段()
#电影配乐
得分=斗志。字段()
#电影上映年份
释放=报废。字段()
#电影时长
持续时间=报废。字段()
(=NationalBureauofStandards)国家标准局
p; # 地区
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属性爬取豆瓣热映的电影信息,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。
内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/84017.html