python爬虫—豆瓣电影海报(按类别)
生活随笔
收集整理的這篇文章主要介紹了
python爬虫—豆瓣电影海报(按类别)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文地址:http://www.alannah.cn/2019/04/06/getdouban/
python爬蟲—豆瓣電影海報
目標:通過python爬蟲在豆瓣電影上按類別對電影海報等數據進行抓取,可以通過更改參數控制抓取數據的數量。
庫:python3.7+selenium+BeautifulSoup
ChromeDriver:https://pan.baidu.com/s/1MBG_AAx-gY5Z5Vc0Qv383A? 提取碼:69eh
由于豆瓣電影的類別網頁是動態加載,不能通過request直接對網頁進行抓取分析,通過selenium在瀏覽器上對網頁源碼進行動態加載然后分析。
由于豆瓣存在反爬蟲策略,如果頻繁的從豆瓣請求,豆瓣會封ip。為了避免被豆瓣偵測到,本人采用了一種較為笨拙的方式,對請求數據設定一定的延遲,不要過于頻繁的獲取數據,延遲設為2s即可,這會導致數據獲取速度較慢。
for item in items:movie = {'img':item.find('img')['src'],'id':item['data-id'],'title':item.find('img')['alt']}time.sleep(2)最終獲取的獲取包含:
1、電影海報,命名格式為-id.jpg
2、info.csv(電影id、電影名稱、上映年份、評分、類型、導演、編劇、主演、國家)
可自行修改網頁分析部分獲取更多的數據
代碼如下:
# -*- coding:utf-8 -*- from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from bs4 import BeautifulSoup from selenium.common.exceptions import ElementNotVisibleException import time import requests import os import csv import re from selenium.common.exceptions import NoSuchElementExceptionclass DBDY:def __init__(self): # 進行初始化操作self.driver = webdriver.Chrome()self.wait = WebDriverWait(self.driver, 20)js = 'window.open("https://www.baidu.com");'self.driver.execute_script(js) # 新建一個標簽頁用于查看電影詳情def open_page(self,type): # 利用selenium驅動,打開豆瓣電影的網頁url = 'https://movie.douban.com/tag/#/?sort=U&range=0,10&tags=電影,'+ typedriver = self.driverdriver.switch_to.window(driver.window_handles[0]) # 定位至總覽標簽頁driver.get(url)driver.refresh() #刷新網頁time.sleep(5)self.get_response(type)def get_response(self,type): # 該函數用來獲取信息driver = self.driverpage = driver.page_source # 獲取網頁源代碼soup = BeautifulSoup(page, 'html.parser')count = 0#加載更多more = soup.find_all('a', class_ = 'more')while(driver.find_element_by_class_name('more') and count<150):try:print('page: ',count)driver.find_element_by_class_name('more').click()count = count + 1time.sleep(3)except ElementNotVisibleException:breakpage = driver.page_source # 獲取網頁源代碼soup = BeautifulSoup(page, 'html.parser')items = soup.find_all('div', class_='cover-wp') # 找到每一部電影的相關信息print('打印網頁信息')for item in items:movie = {'img':item.find('img')['src'],'id':item['data-id'],'title':item.find('img')['alt']}time.sleep(2)is_Exist = self.download_poster_img(movie['img'],type,movie['id']) #下載海報if not is_Exist: #判斷當前電影是否存在self.get_info(movie['title'],type,movie['id'],'https://movie.douban.com/subject/')def get_info(self,title,movie_type,movie_id,url):try:driver = self.driverdriver.switch_to.window(driver.window_handles[1]) #定位至詳情標簽頁driver.get(url + movie_id + '/?tag='+movie_type+'&from=gaia') #打開電影詳情頁pagesource = driver.page_source#讀取電影信息info = driver.find_element_by_id('info').find_elements_by_tag_name('span')#電影評分rating = driver.find_element_by_tag_name('strong').text#上映年份year = driver.find_element_by_class_name('year').textyear = year.replace('(', '')year = year.replace(')', '')#主演actor = driver.find_element_by_class_name('actor').textactor = str.split(actor,':')[-1]actor = actor.replace(' ','')actor = actor.replace('/更多...','')#電影類型type_span = driver.find_elements_by_xpath(".//span[@property='v:genre']")type = ''for item in type_span:type = type + item.text + '/'#制片國家/地區#由于該內容在網頁中特殊,采用正則表達式對其進行搜索#'<span class="pl">制片國家/地區:</span> 英國<br />'expression = r'(?<=<span class="pl">制片國家/地區:</span>).+?(?=<br />)'pattern = re.compile(expression) #編譯正則表達式matcher = re.search(pattern,pagesource) #搜索匹配項country = matcher.group(0)country = country.replace(' ','')movie = {'id':movie_id,'title':title,'year':year,'rating':rating,'type':type,'director':info[2].text,'screenwriter':info[5].text,'actor':actor,'country':country}print(movie)self.record_info(movie)except NoSuchElementException:print('該電影信息不完善')try:os.remove('poster_img/'+movie_id+'.jpg')except FileNotFoundError:returndef download_poster_img(self,url,type,movie_id): #下載海報圖片res = requests.get(url)file_name = str.split(url, '/')[-1]img_type = str.split(file_name,'.')[-1]file_path = 'poster_img/' + movie_id + '.' + img_typeis_Exist = os.path.exists(file_path)if not is_Exist:print('download img file_path = ', file_path)with open(file_path, 'wb') as f:f.write(res.content)return is_Existdef record_info(self,movie): #記錄電影信息file = open('poster_img/info.csv','a',newline='',encoding='utf-8-sig')writer = csv.writer(file,dialect='excel')info = [movie['id'],movie['title'],movie['year'],movie['rating'],movie['type'],movie['director'].replace(' / ','/'),movie['screenwriter'].replace(' / ','/'),movie['actor'].replace(' / ', '/'),movie['country']]writer.writerow(info)file.close()if __name__ == '__main__':#movie_type = ['劇情', '喜劇', '動作', '愛情', '科幻', '動畫', '懸疑', '驚悚', '恐怖', '犯罪', '戰爭']movie_type = ['犯罪', '戰爭']db = DBDY()for type in movie_type: #遍歷所有電影類型print('正在爬取'+type+'電影')db.open_page(type)# 抓取完所有的信息后關閉網頁db.driver.quit()?
總結
以上是生活随笔為你收集整理的python爬虫—豆瓣电影海报(按类别)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大连理工大学网络综合实验三:交换机端口配
- 下一篇: 三字棋游戏的的设计和代码