摘要:处理爱好的目的,我看了看豆瓣热映的电影列表。于是我写了这个爬虫把豆瓣热映的电影都爬了下来。超时异常爬虫定义按照属性名,我们取出所有的影片信息。注意取出属性的写法。执行验证还是老样子,不直接使用命令,构造一个执行。
目录
我喜欢看电影,可以说大部分热门的电影我都看过。处理爱好的目的,我看了看豆瓣热映的电影列表。于是我写了这个爬虫把豆瓣热映的电影都爬了下来。对页面的处理主要是需要点击显示全部电影,然后爬取影片属性,最后输出文本。采用的还是scrapy框架。顺便聊聊我的实现过程吧。
声明一下:本文主要是研究使用,没有别的用途。
GitHub仓库地址:github项目仓库
主要爬取页面为:https://movie.douban.com/cinema/nowplaying/nanjing/
至于后面的地区,可以按照自己的需要改一下,不过多赘述了。页面需要点击一下展开全部影片,才能显示全部内容,不然只有15部。所以我们使用selenium的时候,需要加一个打开页面后的点击逻辑。页面图如下:
通过F12展开的源码,用xpath helper工具验证一下右键复制下来的xpath路径。
为了避免布局调整导致找不到,我把xpath改为通过class名获取。
然后看看每个影片的信息。
分析一下,是不是可以通过nowplaying的div,作为根节点,然后获取下面class为list-item的节点,里面的属性就是我们要的内容。
没什么问题,那么就按照这个思路开始创建项目编码吧。
创建一个较douban_playing的项目,使用scrapy命令。
scrapy startproject douban_playing
定义电影信息实体。
# Define here the models for your scraped items## See documentation in:# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass DoubanPlayingItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() # 电影名 title = 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.htmlimport timefrom scrapy import signals# useful for handling different item types with a single interfacefrom itemadapter import is_item, ItemAdapterfrom scrapy.http import HtmlResponsefrom selenium.common.exceptions import TimeoutExceptionclass 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 scrapyfrom selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsfrom douban_playing.items import DoubanPlayingItemclass 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 interfacefrom itemadapter import ItemAdapterclass 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.htmlBOT_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 rulesROBOTSTXT_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.htmlSPIDER_MIDDLEWARES = { "douban_playing.middlewares.DoubanPlayingSpiderMiddleware": 543,}# Enable or disable downloader middlewares# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.htmlDOWNLOADER_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.htmlITEM_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的位置。
看一下执行后的结果。
完美!!!
最近都在写一些爬虫的案例,也是边学习边摸索,把一些实现过程记录一下,也分享一下,等过段时间还可以回忆回忆。
分享:
情之一字,不知所起,不知所栖,不知所结,不知所解,不知所踪,不知所终。 ——《雪中悍刀行》
如果本文对你有用的话,请不要吝啬你的赞,谢谢!
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/123094.html
摘要:前言新接触爬虫,经过一段时间的实践,写了几个简单爬虫,爬取豆瓣电影的爬虫例子网上有很多,但都很简单,大部分只介绍了请求页面和解析部分,对于新手而言,我希望能够有一个比较全面的实例。 0.前言 新接触爬虫,经过一段时间的实践,写了几个简单爬虫,爬取豆瓣电影的爬虫例子网上有很多,但都很简单,大部分只介绍了请求页面和解析部分,对于新手而言,我希望能够有一个比较全面的实例。所以找了很多实例和文...
摘要:本文内容爬取豆瓣电影页面内容,字段包含排名,片名,导演,一句话描述有的为空,评分,评价人数,上映时间,上映国家,类别抓取数据存储介绍爬虫框架教程一入门创建项目创建爬虫注意,爬虫名不能和项目名一样应对反爬策略的配置打开文件,将修改为。 本文内容 爬取豆瓣电影Top250页面内容,字段包含:排名,片名,导演,一句话描述 有的为空,评分,评价人数,上映时间,上映国家,类别 抓取数据存储 ...
摘要:注一篇去年的旧文,发现没在知乎发过,过来补个档。于是就有了我们这个小项目电影票比价网在我们这个网页上,会展示出当前热映的电影。涉及到模块主要是用来匹配不同渠道的影院信息代码结构项目主要有三块使用豆瓣每日更新上映的影片列表。 注:一篇去年的旧文,发现没在知乎发过,过来补个档。有个小问题是项目中淘票票的网页反爬提升且变动较多,目前暂不可用了。 时常有同学会问我类似的问题:我已经学完了 Py...
摘要:楚江数据是专业的互联网数据技术服务,现整理出零基础如何学爬虫技术以供学习,。本文来源知乎作者路人甲链接楚江数据提供网站数据采集和爬虫软件定制开发服务,服务范围涵盖社交网络电子商务分类信息学术研究等。 楚江数据是专业的互联网数据技术服务,现整理出零基础如何学爬虫技术以供学习,http://www.chujiangdata.com。 第一:Python爬虫学习系列教程(来源于某博主:htt...
摘要:概述在前面两篇爬虫学习之基于的网络爬虫和爬虫学习之简单的网络爬虫文章中我们通过两个实际的案例,采用不同的方式进行了内容提取。 概述 在前面两篇(爬虫学习之基于Scrapy的网络爬虫和爬虫学习之简单的网络爬虫)文章中我们通过两个实际的案例,采用不同的方式进行了内容提取。我们对网络爬虫有了一个比较初级的认识,只要发起请求获取响应的网页内容,然后对内容进行格式化存储。很多时候我们抓取到的内容...
阅读 2348·2021-11-16 11:45
阅读 3722·2021-11-11 16:55
阅读 2317·2021-10-11 10:59
阅读 2019·2021-10-08 10:05
阅读 3476·2021-09-23 11:30
阅读 2190·2021-09-07 09:58
阅读 3032·2021-09-02 15:34
阅读 561·2019-08-30 15:55