zoukankan      html  css  js  c++  java
  • 使用urllib2简单爬取并保存内涵吧内涵段子指定分页的的描述信息

    [内涵8的内涵段子](url https://www.neihan8.com/article/) 爬取每个分页上面显示的描述信息,按回车键继续对下一页进行爬取,输入quit退出爬取。
    思路:

    1. 爬取每个页面的源码
    2. 对源码进行处理(使用正则),获取指定信息
    3. 保存信息
    

    源码如下:

    # -*- coding:utf-8 -*-
    #!/usr/bin/env python
    import urllib2
    import re
    
    
    
    def writepage(content,page):
        '''
        保存爬取结果
        '''
        print('正在保存第' + page + '页')
        filename = '第' + page + '.txt'
        with open(filename,'w') as f:
            f.write(content)
    
    
    
    def loadpage(url,page):
        '''
        爬取指定页的描述信息
        '''
        print('正在下载第' + page + '页')
        headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36"}
        request = urllib2.Request(url,headers=headers)
        response = urllib2.urlopen(request)
        html = response.read()
    
        # 使用正则,获取并返回要爬取的信息
        pattern = re.compile('<div class="desc">.*?</div>')
        m = pattern.findall(html)
        content = ''
        for n in m:
            n = n.replace('<div class="desc">', '').replace('</div>', '') + '
    
    '
            content += n
        return content
    
    
    def neihan8spider(url,page):
        '''
        内涵8段子调度器,爬取并保存处理后的结果
        '''
        print('开始爬取')
    
        # 爬取开关
        switch = True
    
        # 开始爬取
        while switch:
            content = loadpage(url,page)
            writepage(content,page)
            s = raw_input('是否继续爬取,按回车继续,输入quit退出:')
            if s == 'quit':
                switch = False
            else:
                page = str(int(page) + 1)
    
        print('爬取结束')
    
    
    
    if __name__ == '__main__':
    
        page = raw_input('请输入要查看第几页的页面数: ')
    
        # 由于第一页和其它页的url不同,所以分别进行处理
        if(page=='1'):
            url = 'https://www.neihan8.com/article/index' + '.html'
        else:
            url = 'https://www.neihan8.com/article/index_'+ page + '.html'
    
        # 爬取并处理保存
        neihan8spider(url,page)
    
    

    代码测试:

  • 相关阅读:
    declaration may not appear after executable statement in block
    linux 管道通信
    用c语言创建双向环形链表
    bash: ./LM35_make_fs: Permission denied 解决办法
    sunzl is not in the sudoers file.This incident will be reported
    基于嵌入式linux路由转发功能的实现
    关于eth0 eth0:1 和eth0.1关系介绍
    软重启
    Android中Serializable和Parcelable序列化对象详解
    公共技术点(Android 动画基础)
  • 原文地址:https://www.cnblogs.com/silence-cc/p/9213999.html
Copyright © 2011-2022 走看看