抓取豆瓣电影TOP100
一、分析豆瓣top页面,构建程序结构
1.首先打开网页http://movie.douban.com/top250?start,也就是top页面
然后试着点击到top100的页面,注意带top100的链接依次为
2.然后通过查看源码,发现电影名的代码如下:
<span class="title">肖申克的救赎</span>
<span class="title"> / The Shawshank Redemption</span>
如图,因为有一些英文名等描述,通过正则抓取有些干扰,可能还需要后续过滤。
根据以上信息,此程序主要分以下3个步骤:
二、构建url地址池
- 抓取top100电影名称
- 依次打印输出
依次写出代码
1.构建url地址池。代码如下:
import urllib2import re# ----------确定url地址池------------pre_url = 'http://movie.douban.com/top250?start='top_urls = []# 因为top100,每页25部电影,故为4页,从零开始for num in range(4): top_urls.append(pre_url + str(num * 25))2.抓取top100电影名称
# ------------抓取top100电影名称----------top_content = []top_tag = re.compile(r'<span class="title">(.+?)</span>')for url in top_urls: content = urllib2.urlopen(url).read() pre_content = re.findall(top_tag, content) # 过滤不符合条件的list,得到最后的top100的list for item in pre_content: if item.find(' ') == -1: top_content.append(item)3.打印输出
top_num = 1for item in top_content: print 'Top' + str(top_num) + ' ' + item top_num += 1三、整理代码
我还是python新手,还没有太多的pythonic思想,也没有代码优化技巧,只能说是整理。
其次,个人习惯,在简单的代码里面我还是喜欢少用函数,尽量不隐藏代码的逻辑。
以下代码请参考,并欢迎提意见,希望得到大家的意见,谢谢!
整理后的代码如下:
抓取用户头像图片
import urllib.requestimport reimport time #获取输入的帖子单页htmldef getHtml2(url2): html2=urllib.request.urlopen(url2).read().decode('utf-8') return html2 #抽取图片相关列表,并下载图片def gettopic(html2): reg2=r'http:///group/kaopulove/discussion?start=%d'%num) topicurl=gettopic(html2) topic_page=getHtml2(topicurl) download_img=download(topic_page) num=page_num*25 page_num+=1 else: print('采集完成!')