zoukankan      html  css  js  c++  java
  • 用python爬取网站文献、新闻报道内容,并保存为文本

      最近同学让我帮忙爬取点工程类的事故案例,目标网站:http://www.mkaq.org/sggl/shigual/,对于java程序员的我,对python还不太熟悉,不过python也很容易学的,主要是学会根据自己需求,用各种库就行了。下面记录一下我从安装环境到代码运行的过程:

    一、安装python环境

      安装python我是参考的这篇文章,写的很详细,python3环境安装

    二、安装需要用到的python的库

    参考这个常用python库安装教程,此爬虫代码只用到了下列这几个库,参照教程安装即可:

        requests
        selenium
        chromedriver
        lxml
        beautifulsoup4 (注意:python2版本用的是beautifulsoup,但是3.版本用的是beautifulsoup4 ,注意版本不同,此处用的为python3.8)

    三、代码编写

      环境准备好以后,开始编写代码:

      

    import os
    import io
    import sys
    import requests
    
    from bs4 import BeautifulSoup
    
    # 改变标准输出的默认编码
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030')
    
    def urlBS(url):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
        }
        resp = requests.get(url, headers=headers)
        html = resp.content.decode('utf-8')
        soup = BeautifulSoup(html, 'html.parser')
        return soup
    
    def main(url):
        soup = urlBS(url)
        # 数据保存的目录( os.getced()创建文件夹)
        path = os.getcwd() + u'/爬取的文章/'
    
        if not os.path.isdir(path):  # 判断是否有这个文件夹
            os.mkdir(path)
    
        # for new in soup.select('.news-box'):
        for new in soup.select('.imgr'):
    
            if len(new.select('h2')) > 0:
                # 获取文章列表连接
                # article_list_url = 'https:' + new.select('a')[0]['href']
                #获取首页数据,不需要添加地址前缀
                # article_list_url = new.select('a')[0]['href']
    
                #获取第二页以后的数据,需要添加地址
                article_list_url = 'http://www.mkaq.org' + new.select('a')[0]['href']
    
                # 输出文章列表连接
                # print(article_ list_ url)
    
                # 获取文章标题
                # title = ''.join(new.select('h4')[0].text.split())
                title = ''.join(new.select('h2')[0].text.split())
    
                # 输出文章标题
                print(title)
    
                # 请求每篇文章
                result = urlBS(article_list_url)
    
                article = []
    
                # 获取article 中被p包含的内容去除最后一个p标签即责任编辑
                for v in result.select(' .article_content p')[:-1]:
                    # 将内容添加到列表中, 并去除两边特殊字符
                    article.append(v.text.strip())
    
                # 将列表中内容以换行连接
                author_info = '
    '.join(article)
    
                # 输出文章内容
                # print(author_ info)
    
                # 保存的文件格式为txt
                filename = path + title + '.txt'
    
                # 输出保存路径
                print(filename)
    
                new = open(filename, 'w', encoding="utf- 8")
    
                # 写入标题
                new.write(title + '
    
    ')
                # 写入内容
                new.write(author_info)
                # 关闭
                new.close()
    
    if __name__ == '__main__':
        # 目标网址
        # firsurl = 'http://www.mkaq.org/sggl/shigual/'
    
        #获取第三页数据,article_list_url也要同步修改
        firsurl = 'http://www.mkaq.org/sggl/shigual/index_3.shtml'
    
        main(firsurl)
        print('执行完成!')

    四、运行效果如下图所示

      

       在获取默写页面数据时,个别文章可能会报错,不用管,忽略即可。

      若要获取其他网站的内容,参考网站源码的标签列表,做对应修改即可。

  • 相关阅读:
    Linux 为linux enterprises 6安装图形桌面教程
    loadrunner 结果分析-loadrunner结果分析
    python 全栈开发,Day91(Vue实例的生命周期,组件间通信之中央事件总线bus,Vue Router,vue-cli 工具)
    python 全栈开发,Day90(Vue组件,前端开发工具包)
    python 全栈开发,Day89(sorted面试题,Pycharm配置支持vue语法,Vue基础语法,小清单练习)
    python 全栈开发,Day88(csrf_exempt,ES6 快速入门,Vue)
    python 全栈开发,Day87(ajax登录示例,CSRF跨站请求伪造,Django的中间件,自定义分页)
    python 全栈开发,Day85(Git补充,随机生成图片验证码)
    python 全栈开发,Day84(django请求生命周期,FBV和CBV,ORM拾遗,Git)
    python 全栈开发,Day83(博客系统子评论,后台管理,富文本编辑器kindeditor,bs4模块)
  • 原文地址:https://www.cnblogs.com/zhangzhiyong-/p/15539573.html
Copyright © 2011-2022 走看看