看了几天的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)