Python 通過xpath屬性爬取豆瓣熱映的電影信息
聲明一下:本文主要是研究使用,沒有別的用途。
GitHub倉庫地址:github項(xiàng)目倉庫
頁面分析
主要爬取頁面為:https://movie.douban.com/cinema/nowplaying/nanjing/
至于后面的地區(qū),可以按照自己的需要改一下,不過多贅述了。頁面需要點(diǎn)擊一下展開全部影片,才能顯示全部內(nèi)容,不然只有15部。所以我們使用selenium的時候,需要加一個打開頁面后的點(diǎn)擊邏輯。頁面圖如下:

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

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

然后看看每個影片的信息。

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

沒什么問題,那么就按照這個思路開始創(chuàng)建項(xiàng)目編碼吧。
實(shí)現(xiàn)過程
創(chuàng)建項(xiàng)目
創(chuàng)建一個較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() # 電影時長 duration = scrapy.Field() # 地區(qū) region = scrapy.Field() # 電影導(dǎo)演 director = scrapy.Field() # 電影主演 actors = scrapy.Field()
中間件操作定義
主要是點(diǎn)擊展開全部影片,需要加一段代碼。
# 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('超時異常:{}'.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)
爬蟲定義
按照屬性名,我們?nèi)〕鏊械挠捌畔?。注意取出屬性的寫法?/p>
#!/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') # 使用無頭谷歌瀏覽器模式
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電影時長:{}\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ī)的,放開幾個默認(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)造一個py執(zhí)行cmd。注意該py的位置。

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

完美?。?!
總結(jié)
最近都在寫一些爬蟲的案例,也是邊學(xué)習(xí)邊摸索,把一些實(shí)現(xiàn)過程記錄一下,也分享一下,等過段時間還可以回憶回憶。
分享:
情之一字,不知所起,不知所棲,不知所結(jié),不知所解,不知所蹤,不知所終。 ——《雪中悍刀行》
如果本文對你有用的話,請不要吝嗇你的贊,謝謝!

以上就是Python 通過xpath屬性爬取豆瓣熱映的電影信息的詳細(xì)內(nèi)容,更多關(guān)于Python 爬蟲豆瓣的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信