爬取豆瓣Top 250的電影,並輸出到文件. demo,學習篇

'''
@time   :2019/213 17:55
@desc   :通過爬取http://movie.douban.com/top250/得到豆瓣Top 250的電影,並輸出到文件movies.txt
'''
# import 導入模塊
import codecs
import requests
# 導入模塊 bs4 的 BeautifulSoup 函數
from bs4 import BeautifulSoup

# 下載網址
DOWNLOAD_URL = 'http://movie.douban.com/top250/'

# def 定義download_page函數 --- 相同於PHP function
def download_page(url):
    # 使用 requests get方法 .content編碼 .text返回頁面文本
    return requests.get(url).content
    #return requests.get(url).text

# 定義parse_html函數
def parse_html(html):
    # 使用 Beautifulsoup解析, 解析器使用 lxml
    soup = BeautifulSoup(html,"lxml")
    # 標籤內容獲取 <ol class="grid_view">
    movie_list_soup = soup.find('ol', attrs={'class': 'grid_view'})
    movie_name_list = []
    # 循環獲取 li->span下標題
    for movie_li in movie_list_soup.find_all('li'):
        detail = movie_li.find('div', attrs={'class': 'hd'})
        # 獲取title
        movie_name = detail.find('span', attrs={'class': 'title'}).getText()
        # append函數會在數組後加上相應的元素
        movie_name_list.append(movie_name)

    # 獲取分頁數據
    next_page = soup.find('span', attrs={'class': 'next'}).find('a')
    if next_page:
        return movie_name_list, DOWNLOAD_URL + next_page['href']
    return movie_name_list, None

# 定義main函數
def main():
    url = DOWNLOAD_URL
    # 寫法可以避免因讀取文件時異常的發生而沒有關閉問題的處理了
    with codecs.open('movies.txt', 'wb', encoding='utf-8') as fp:
        while url:
            html = download_page(url)
            movies, url = parse_html(html)
            fp.write(u'{movies}\n'.format(movies='\n'.join(movies)))

# _name__ 是當前模塊名,當模塊被直接運行時模塊名爲 __main__ 。當模塊被直接運行時,代碼將被運行,當模塊是被導入時,代碼不被運行。
if __name__ == '__main__':
    main()

 

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