平時利用在地鐵公交的時間簡單學習瞭解了 Python,學習參考的是廖雪峯的Python教程 ,但是要想學好,還是要上手練習纔會有好的效果,於是週末就利用 Python 寫了一個簡單的爬蟲,來獲取豆瓣電影排行榜 Top250 的數據,實現了保存數據到文件,保存海報圖片。
我利用的是 requests (HTTP for Humans ,哈哈)和 BeautifulSoup,具體使用方法可參考官網,安裝方式:
sudo pip install requests
sudo pip install beautifulsoup4
安裝好以後就可以開始了,首先打開豆瓣電影排行榜,查看網頁源碼
箭頭部分就是我們需要的數據,包括:排名,名字,評分,評分人數,短評,同時當我們查看下一頁的時候,發現鏈接格式是這樣的
“https://movie.douban.com/top250?start=25”
我們可以得知網頁是按 25 來分頁的,於是代碼如下:
def movies_spider(start):
global file_content
url = "https://movie.douban.com/top250?start=%d" % start
response = requests.get(url).text
soup = BeautifulSoup(response)
movie_list = soup.find_all('div', {'class': 'item'})
for item in movie_list:
order = int(item.find('em').string)
icon_path = item.find('img').get('src')
info = item.find('div', {'class': 'info'})
name = info.find('span', {'class': 'title'}).string
save_pic(icon_path, name)
rating_num = info.find('span', {'class': 'rating_num'}).string
total = info.find('span', {'class': 'rating_num'}).find_next_sibling().find_next_sibling().string
inq = info.find('span', {'class': 'inq'})
try:
quote = inq.get_text()
except AttributeError:
quote = 'None'
print("Type error")
file_content += "%d\t%s\t評分:%s\n\t%s\t簡評:%s\n\n" % (order, name, rating_num, total, quote)
這就是核心部分,其實只要結合 BeautifulSoup 的文檔以及網頁源碼,還是挺容易理解的,那剩下的部分就是保存文件和保存圖片,代碼已經放到 Github ,有需要的可前往查看 Github
參考鏈接