当前位置:   article > 正文

python爬豆瓣电影Top250_item.find(" ")==-1

item.find(" ")==-1

1.前期分析

完成豆瓣电影Top250网站https://movie.douban.com/top250)推荐电影名单的爬取 。
这里写图片描述

这里写图片描述

可见每页显示25部电影,总共10页.

chrome按F12:
这里写图片描述

所以用正则表达式表示为

<span.*?class="title">(.*?)</span>
  • 1

但符合这样的有两行:

<span class="title">肖申克的救赎</span>
<span class="title">&nbsp;/&nbsp;The Shawshank Redemption</span>
  • 1
  • 2

我们需要提取的是第一行,所以我们还要在代码中过滤掉:

&nbsp;/&nbsp;The Shawshank Redemption
  • 1

2.决战代码

注释详细,应该好懂..

#coding:utf8

import urllib2
import re

__author__ = 'binchasing'
'''
爬取豆瓣电影Top250 网站:https://movie.douban.com/top250
'''
class douban_movie():
    def __init__(self):
        self.my_url = r'https://movie.douban.com/top250'  #豆瓣Top250首页
        self.top_num = 1   #记录即将输出的电影编号
        self.total_page_num = 10   #网站每页记录25部电影,所有250部电影总共有10页

    '''
    get_page_html(self,page_index)返回相应页码的网页html内容
    page_index:页码编号,0表示第一页
    contents:返回相应网页的html

    '''
    def get_page_html(self,page_index):    
        cur_url =  self.my_url + '?start=' + str(25*page_index) + '&filter='   #第(page_index+1)页的url
        request = urllib2.Request(cur_url)      #创建请求
        response = urllib2.urlopen(request)     #得到响应
        contents = response.read()
        return contents
    '''
    print_movie(self,contents) 打印对应网页中的电影名称
    contents:网页的html
    '''
    def print_movie(self,contents):
        pattern = re.compile(r'<span.*?class="title">(.*?)</span>',re.S)       #构造正则表达式
        movie_items = re.findall(pattern,contents)   #找出所有匹配项
        for ind, item in enumerate(movie_items) :
            if item.find("&nbsp") == -1 :   #排除不满足条件的匹配项
                print ("Top" + str(self.top_num) + " " + item).decode("utf-8")  #utf-8转为unicode输出
                self.top_num = self.top_num + 1     #电影编号自增

    '''
    start_spider(self)启动爬虫
    '''
    def start_spider(self):
        index = 0
        while index < self.total_page_num:   #打印所有页
            contents = self.get_page_html(index)
            self.print_movie(contents)
            index = index + 1
def main():
    print '''
    ------------------《豆瓣Top250榜单》------------------
    '''
    douban = douban_movie()
    douban.start_spider()

if __name__ == '__main__':
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

3.输出结果

这里写图片描述
………
这里写图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/720748
推荐阅读
相关标签
  

闽ICP备14008679号