Python爬蟲 -- 抓取電影天堂8分以上電影


看了幾天的python語法,還是應該寫個東西練練手。剛好假期里面看電影,找不到很好的影片,於是有個想法,何不搞個爬蟲把電影天堂里面8分以上的電影爬出來。做完花了兩三個小時,擼了這么一個程序。反正蠻簡單的,思路和之前用nodejs寫爬蟲一樣。

爬蟲的入口從分頁的列表開始,比如美劇的列表第一頁地址這樣: http://www.ygdy8.net/html/gndy/oumei/list_7_1.html,第二頁是http://www.ygdy8.net/html/gndy/oumei/list_7_2.html,是有規律的,所以就可以遍歷所有的頁面,分別抓取每頁里面的影視資源,再進入每條電影的詳情頁面,抓取出下載地址,存到文件里。

技術上用的是requests 和 BeautifulSoup兩個模塊。

具體做法是,先從電影列表中定位每條資源中的IMDB(b)評分大於8分的資源,並且將結果放入movie對象中。

class Movie:

    def __init__(self, name, url, score, link):
        self.name = name
        self.url = url
        self.score = score
        self.link = link

    def __str__(self):
        return '%s,\t%s分,\t%s' % (self.name, self.score, self.link)

    __repr__ = __str__

# 過濾資源
def filterMovie(url):
    resultList = []
    soup = getSoup(url)
    tables = soup.find_all('table', class_='tbspan')
    for table in tables:
        nameA = table.find('a', text=re.compile("《"))
        td = table.find('td', text=re.compile("IMD"))
        if td is not None:
            scoreStr = re.findall(r"評分 (.+?)/10", td.text)
            if(len(scoreStr) > 0):
                try:
                    score = float(scoreStr[0])
                    if(score > 8):
                        name = nameA.text
                        url = site + nameA['href']
                        print('url:', url)
                        print('title:', name)
                        print('score:', score)
                        downloadLink = getDownloadLink(url)
                        movie = Movie(name, url, score, downloadLink)
                        resultList.append(movie)
                except:
                    print('error !!')
    return resultList

其中的getDownloanLink(url)是進入電影詳情頁獲取下載鏈接。

def getDownloadLink(url):
    soup = getSoup(url)
    downloadTd = soup.find('td', attrs={"style": "WORD-WRAP: break-word"})
    downloadA = downloadTd.find('a')
    return downloadA['href']

然后是將電影信息存入到文件data.txt中。

def saveInfo(movieList):
    fileObj = open('data.txt', 'a')
    for movie in movieList:
        movie_str = str(movie)
        print('movie info:', movie_str)
        global lineNo
        fileObj.write('(' + str(lineNo) + ') ' + movie_str)
        fileObj.write('\n')
        fileObj.write('———————————')
        fileObj.write('\n')
        lineNo += 1
    fileObj.close()

經過上面的步驟,即可將某一頁的電影資源抓取到,並且存入文件中。

程序的主入口,遍歷列表即可。目前他們只有155頁,就限制這么多頁碼。

if __name__ == '__main__':
    for index in range(156):
        index += 1
        url = 'http://www.ygdy8.net/html/gndy/oumei/list_7_' + \
            str(index) + '.html'
        getPageResource(url)

具體代碼在github中,傳送門,爬到的結果也放入代碼倉庫中了。有興趣的,可以下載看看。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM