Python自定義豆瓣電影種類,排行,點評的爬取與存儲(初級)

Python 2.7 
IDE Pycharm 5.0.3 
Firefox 47.0.1

具體Selenium和PhantomJS配置及使用請看調用PhantomJS.exe自動續借圖書館書籍


網上一溜豆瓣TOP250---有意思麼?

起因

就是想寫個豆瓣電影的爬取,給我電影荒的同學。。。。當然自己也練手啦


目的

1.根據用戶輸入,列出豆瓣高分TOP(用戶自定義)的電影,鏈接,及熱評若干。 
2.製作不需要Python環境可運行的exe,但由於bug未修復,需要火狐瀏覽器支持


方案

使用PhantomJS+Selenium+Firefox實現


實現過程

1.get到首頁後,根據選擇,點擊種類,然後根據輸入需求,進行排序 
2.抓取每個電影及超鏈接,進入超鏈接後,抓取當前電影的熱評及長評 
3.當用戶所要求TOP數目大於第一頁的20個時候,點擊加載更多,再出現20個電影,重複2操作。


以豆瓣高分,然後按評分排序的點擊過程(其餘操作一致,先種類後排序選擇,再爬)

這裏寫圖片描述


實現代碼

# -*- coding: utf-8 -*-
#Author:哈士奇說喵
#爬豆瓣高分電影及hot影評

from selenium import webdriver
import selenium.webdriver.support.ui as ui
import time


print "---------------system loading...please wait...---------------"
SUMRESOURCES = 0 #全局變量
driver_detail = webdriver.PhantomJS(executable_path="phantomjs.exe")
#driver_item=webdriver.PhantomJS(executable_path="phantomjs.exe")
driver_item=webdriver.Firefox()
url="https://movie.douban.com/"
#等待頁面加載方法
wait = ui.WebDriverWait(driver_item,15)
wait1 = ui.WebDriverWait(driver_detail,15)


#獲取URL和文章標題

def getURL_Title():
    global SUMRESOURCES

##############################################################################
#需要鍵入想要獲取的信息,比如種類,排序方式,想看多少內容
##############################################################################

    print "please select:"
    kind=input("1-Hot\n2-Newest\n3-Classics\n4-Playable\n5-High Scores\n6-Wonderful but not popular\n7-Chinese film\n8-Hollywood\n9-Korea\n10-Japan\n11-Action movies\n12-Comedy\n13-Love story\n14-Science fiction\n15-Thriller\n16-Horror film\n17-Cartoon\nplease select:")
    print "--------------------------------------------------------------------------"
    sort=input("1-Sort by hot\n2-Sort by time\n3-Sort by score\nplease select:")
    print "--------------------------------------------------------------------------"
    number = input("TOP ?:")
    print "--------------------------------------------------------------------------"
    ask_long=input("don't need long-comments,enter 0,i like long-comments enter 1:")
    print "--------------------------------------------------------------------------"
    global save_name
    save_name=raw_input("save_name (xx.txt):")
    print "---------------------crawling...---------------------"

    driver_item.get(url)

##############################################################################
#進行網頁get後,先進行電影種類選擇的模擬點擊操作,然後再是排序方式的選擇
#最後等待一會,元素都加載完了,才能開始爬電影,不然元素隱藏起來,不能被獲取
#wait.until是等待元素加載完成!
##############################################################################

    wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div/div/label[%s]"%kind))
    driver_item.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div/div/label[%s]"%kind).click()
    wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div[3]/div/label[%s]"%sort))
    driver_item.find_element_by_xpath("//div[@class='fliter-wp']/div/form/div[3]/div/label[%s]"%sort).click()

    num=number+1#比如輸入想看的TOP22,那需要+1在進行操作,細節問題
    time.sleep(2)

    #打開幾次“加載更多”
    num_time = num/20+1
    wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='list-wp']/a[@class='more']"))

    for times in range(1,num_time):
        time.sleep(1)
        driver_item.find_element_by_xpath("//div[@class='list-wp']/a[@class='more']").click()
        time.sleep(1)
        wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='list']/a[%d]"%num))
        #print '點擊\'加載更多\'一次'

    #使用wait.until使元素全部加載好能定位之後再操作,相當於try/except再套個while把

    for i in range(1,num):
        wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='list']/a[%d]"%num))
        list_title=driver_item.find_element_by_xpath("//div[@class='list']/a[%d]"%i)
        print '----------------------------------------------'+'NO' + str(SUMRESOURCES +1)+'----------------------------------------------'
        print u'電影名: ' + list_title.text
        print u'鏈接: ' + list_title.get_attribute('href')
        #print unicode碼自動轉換爲utf-8的


        #寫入txt中部分1
        list_title_wr=list_title.text.encode('utf-8')#unicode碼,需要重新編碼再寫入txt
        list_title_url_wr=list_title.get_attribute('href')

        Write_txt('\n----------------------------------------------'+'NO' + str(SUMRESOURCES +1)+'----------------------------------------------','',save_name)
        Write_txt(list_title_wr,list_title_url_wr,save_name)

        SUMRESOURCES = SUMRESOURCES +1

        try:#獲取具體內容和評論。href是每個超鏈接也就是資源單獨的url
            getDetails(str(list_title.get_attribute('href')),ask_long)
        except:
            print 'can not get the details!'


##############################################################################
#當選擇一部電影后,進入這部電影的超鏈接,然後才能獲取
#同時別忽視元素加載的問題
#在加載長評論的時候,注意模擬點擊一次小三角,不然可能會使內容隱藏
##############################################################################
def getDetails(url,ask_long):

    driver_detail.get(url)
    wait1.until(lambda driver: driver.find_element_by_xpath("//div[@id='link-report']/span"))
    drama = driver_detail.find_element_by_xpath("//div[@id='link-report']/span")
    print u"劇情簡介:"+drama.text
    drama_wr=drama.text.encode('utf-8')
    Write_txt(drama_wr,'',save_name)
    print "--------------------------------------------Hot comments TOP----------------------------------------------"
    for i in range(1,5):#四個短評
        try:
            comments_hot = driver_detail.find_element_by_xpath("//div[@id='hot-comments']/div[%s]/div/p"%i)
            print u"最新熱評:"+comments_hot.text
            comments_hot_wr=comments_hot.text.encode('utf-8')
            Write_txt("--------------------------------------------Hot comments TOP%d----------------------------------------------"%i,'',save_name)
            Write_txt(comments_hot_wr,'',save_name)
        except:
            print 'can not caught the comments!'


    #加載長評
    if ask_long==1:
        try:
            driver_detail.find_element_by_xpath("//img[@class='bn-arrow']").click()
            #wait.until(lambda driver: driver.find_element_by_xpath("//div[@class='review-bd']/div[2]/div/div"))
            time.sleep(1)
            #解決加載長評會提示劇透問題導致無法加載
            comments_get = driver_detail.find_element_by_xpath("//div[@class='review-bd']/div[2]/div")
            if comments_get.text.encode('utf-8')=='提示: 這篇影評可能有劇透':
                comments_deep=driver_detail.find_element_by_xpath("//div[@class='review-bd']/div[2]/div[2]")
            else:
                comments_deep = comments_get
            print "--------------------------------------------long-comments---------------------------------------------"
            print u"深度長評:"+comments_deep.text
            comments_deep_wr=comments_deep.text.encode('utf-8')
            Write_txt("--------------------------------------------long-comments---------------------------------------------\n",'',save_name)
            Write_txt(comments_deep_wr,'',save_name)
        except:
            print 'can not caught the deep_comments!'


##############################################################################
#將print輸出的寫入txt中查看,也可以在cmd中查看,換行符是爲了美觀
##############################################################################
def Write_txt(text1='',text2='',title='douban.txt'):

        with open(title,"a") as f:
            for i in text1:
                f.write(i)
            f.write("\n")
            for j in text2:
                f.write(j)
            f.write("\n")

def main():

    getURL_Title()
    driver_item.quit()

main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161

上面的代碼是可以實現的,但需要Firefox的配合,因爲我其中一個引擎調用了Firefox,另一個抓評論的用了PhantomJS。


實現效果

這裏直接上傳打包成exe後的形式,如何打包exe請看將python打包成exe

這裏寫圖片描述

存入的txt文件 
這裏寫圖片描述

因爲打包成exe必須是中文的鍵入,所以沒辦法,我改成英文來着,不然會出現這種情況。。。 
這裏寫圖片描述

輸出內容是沒有問題的。。。。。。


問題及解決方案

1.使用PhantomJS和Firefox出現不同效果的問題,第21個回到起點。 
1.解決方案,暫且我也沒有找到,只有調用Firefox然後完事後再關閉,分析請見僞解決Selenium中調用PhantomJS無法模擬點擊(click)操作 


2.在對unicode輸出在txt出現的問題,但是在print可以直接中文輸出的。 
2.解決方案:詳見Python輸出(print)內容寫入txt中保存 


Pay Attention

這裏和上篇 僞解決Selenium中調用PhantomJS無法模擬點擊(click)操作 

這裏解決的問題和昨天的Pay Attention是一樣的,本來程序也是增強性補充而已,所以重複了。

1.元素無法定位問題 
1.解決方案,首先查看是不是隱藏元素,其次再看自己的規則有沒有寫錯,還有就是是不是頁面加載未完成,詳見解決網頁元素無法定位(NoSuchElementException: Unable to locate element)的幾種方法 


2.只採集自己需要的數據,剔除無用數據,比如說,剛開始我用

driver_detail.find_elements_by_xpath
  • 1
  • 1

然後寫個取出list中元素的方法,但是這樣的話,一個便籤下內容未必太多,並不是我想要的如圖:

這裏寫圖片描述

比如說,我只想要紅色的部分,那麼,採取elements就不太好處理。

2.解決方案,我採用的方法是格式化字符串!這個方法我在Selenium+PhantomJS自動續借圖書館書籍(下)也用過,根據元素的特性,可以發現,每個熱評的正文標籤不一樣的,其餘標籤一樣,只要格式化正文標籤即可,像這樣

for i in range(1,5):#取了前四條熱評
        try:
            comments = driver_detail.find_element_by_xpath("//div[@id='hot-comments']/div[%s]/div/p"%i)
            print u"最新熱評:"+comments.text
        except:
            print 'can not caught comments!'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.一個引擎幹有個事!我現在沒辦法,只有將第一個需要處理的頁面用Firefox來處理,之後評論用PhantomJS來抓取,之後可以用quit來關閉瀏覽器,但是啓動瀏覽器還是會耗費好多資源,而且挺慢,雖然PhantomJS也很慢,我12G內存都跑完了。。。。。。看樣子是給我買8x2 16G雙通道的藉口啊。


4.備註不標準也會導致程序出錯,這個是我沒想到的,我一直以爲在”’備註”’之間的都可以隨便來,結果影響程序運行了,之後分模塊測試才注意到這個問題,也是以前沒有遇到過的,切記!需要規範自己代碼,特別是像Python這樣縮進是靈魂的語言。。。。


5.補充,長評論的抓取

這裏寫圖片描述

這是點擊之後的圖,可以看到元素定位也是不一樣的,注意

這裏寫圖片描述


最後

今天在知乎上回答了個問題,能幫助和吸引一些人過來學這門讓人上癮的語言感覺很有成就感啊,哈哈哈 
希望能幫助更多的人,同時請不吝賜教!


PS

知乎關注我有毛用,還不如這裏呢。感興趣的可以下載exe文件,已打包上傳資源 
這裏寫圖片描述


致謝

@MrLevo520–僞解決Selenium中調用PhantomJS無法模擬點擊(click)操作 
@MrLevo520–Python輸出(print)內容寫入txt中保存 
@MrLevo520–解決網頁元素無法定位(NoSuchElementException: Unable to locate element)的幾種方法 
@Eastmount–[Python爬蟲] Selenium+Phantomjs動態獲取CSDN下載資源信息和評論 
@Eastmount–[Python爬蟲] 在Windows下安裝PIP+Phantomjs+Selenium 
@MrLevo520–解決Selenium彈出新頁面無法定位元素問題(Unable to locate element)

1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章