• Python3.5:爬取网站上电影数据


    首先我们导入几个pyhton3的库:

    from urllib import request
    import urllib
    from html.parser import HTMLParser

    在Python2和Python3之间一个重要区别就是,在Python2有urllib,urllib2两个库,在Python3整合到一起,里面的函数方式也有一点变,先定义一个函数,将header,url,request,都打包成一个函数方便调用,且看下面代码:

    def print_movies(url):
        # 伪装成浏览器访问网站,但其实没啥用,很容易被中间件检测出来,但没有又不行,所以蛮写吧
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}
        # Python3的urllib
        req = urllib.request.Request(url, headers=header)
        s = urllib.request.urlopen(req)
        parser = MovieParser()
        parser.feed((s.read()).decode('utf-8'))
        s.close()

    再重载HTMLParser库的handle_starttag(self, tag, attrs),系统就会默认调用用户重载的,具体调用方式在官方文档里面详细介绍:HTMLParser,

    class MovieParser(HTMLParser):
        def __init__(self):
            HTMLParser.__init__(self)
            self.movies = []
            # 重载HTMLParser自带的函数
        def handle_starttag(self, tag, attrs):
            def _attr(attrlist, attrname):
                for attr in attrlist:
                    if attr[0] == attrname:
                        return attr[1]
                return None
            # 可以在这class后面找到每个li标签的特征属性比如catrgory在下面判断
            if tag == 'li' and _attr(attrs, 'data-title'):
                movie= {}
                movie['title'] = _attr(attrs, 'data-title')
                movie['rate'] = _attr(attrs, 'data-rate')
                movie['director'] = _attr(attrs, 'data-director')
                movie['actors'] = _attr(attrs, 'data-actors')
                self.movies.append(movie)
                print('%(title)s|%(rate)s|%(director)s|%(actors)s' % movie)

    当我们执行到parser.feed((s.read()).decode('utf-8'))时,知道为什么要这样写,首先parser时HTMLParser的子类所以包括feed(),在注入数据时,s.read()是返回bytes类型,但feed()只接受str类型,所以直接在后面加个decode('utf-8')即转码(三个bytes转换为一个中文),又可以转换为str,基本获取数据就这么简单,要是想获取别的网站的数据,可以换个url和条件判断就可以了,我把全部代码贴上来:

    from urllib import request
    import urllib
    from html.parser import HTMLParser
    
    class MovieParser(HTMLParser):
        def __init__(self):
            HTMLParser.__init__(self)
            self.movies = []
            # 重载HTMLParser自带的函数
        def handle_starttag(self, tag, attrs):
            def _attr(attrlist, attrname):
                for attr in attrlist:
                    if attr[0] == attrname:
                        return attr[1]
                return None
            # 可以在这class后面找到每个li标签的特征属性比如catrgory在下面判断
            if tag == 'li' and _attr(attrs, 'data-title'):
                movie= {}
                movie['title'] = _attr(attrs, 'data-title')
                movie['rate'] = _attr(attrs, 'data-rate')
                movie['director'] = _attr(attrs, 'data-director')
                movie['actors'] = _attr(attrs, 'data-actors')
                self.movies.append(movie)
                print('%(title)s|%(rate)s|%(director)s|%(actors)s' % movie)
    
    def print_movies(url):
        # 伪装成浏览器访问网站,但其实没啥用,很容易被中间件检测出来,但没有又不行,所以蛮写吧
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}
        # Python3的urllib
        req = urllib.request.Request(url, headers=header)
        s = urllib.request.urlopen(req)
        parser = MovieParser()
        parser.feed((s.read()).decode('utf-8'))
        s.close()
    
    
    if __name__ == '__main__':
        url = 'https://movie.douban.com/'
        # 返回一个电影列表
        print_movies(url)

    运行结果为:

  • 相关阅读:
    压测mysql连接数
    OpenStack SR-IOV
    Scheduler 租户虚机到不同host
    Neutron 集成 DPDK
    Centos 7 密码重置
    win10优化
    Aria
    tomcat lb cluster
    Tomcat.md
    varnish.md
  • 原文地址:https://www.cnblogs.com/doudoublog/p/7362355.html
Copyright © 2020-2023  润新知