'''
@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()