看了幾天的python語法,仍是應該寫個東西練練手。恰好假期裏面看電影,找不到很好的影片,因而有個想法,何不搞個爬蟲把電影天堂裏面8分以上的電影爬出來。作完花了兩三個小時,擼了這麼一個程序。反正蠻簡單的,思路和以前用nodejs寫爬蟲同樣。html
爬蟲的入口從分頁的列表開始,好比美劇的列表第一頁地址這樣: http://www.ygdy8.net/html/gndy/oumei/list_7_1.html
,第二頁是http://www.ygdy8.net/html/gndy/oumei/list_7_2.html
,是有規律的,因此就能夠遍歷全部的頁面,分別抓取每頁裏面的影視資源,再進入每條電影的詳情頁面,抓取出下載地址,存到文件裏。node
技術上用的是requests 和 BeautifulSoup兩個模塊。python
具體作法是,先從電影列表中定位每條資源中的IMDB(b)評分大於8分的資源,而且將結果放入movie對象中。git
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)
是進入電影詳情頁獲取下載連接。github
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中。app
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()
通過上面的步驟,便可將某一頁的電影資源抓取到,而且存入文件中。url
程序的主入口,遍歷列表便可。目前他們只有155頁,就限制這麼多頁碼。spa
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)