zoukankan      html  css  js  c++  java
  • 爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离

     

    1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文、show-info。

    2. 分析info字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。

    3. 将字符串格式的发布时间转换成datetime类型

    4. 使用正则表达式取得新闻编号

    5. 生成点击次数的Request URL

    6. 获取点击次数

    7. 将456步骤定义成一个函数 def getClickCount(newsUrl):

    8. 将获取新闻详情的代码定义成一个函数 def getNewDetail(newsUrl):

    9. 尝试用使用正则表达式分析show info字符串,点击次数字符串。

    import re
    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(newsurl) #返回response对象
    res.encoding='utf-8'
    soup = BeautifulSoup(res.text,'html.parser')
    #循环遍历打印
    def getNewDetail(newsurl1):
        for news in soup.select('li'):
            if len(news.select('.news-list-title'))>0:
                title=news.select('.news-list-title')[0].text
                descript=news.select('.news-list-description')[0].text
                a=news.a.attrs['href']
                p=news.span.text
                time=datetime.strptime(p,'%Y-%m-%d')
                print("发布时间:",time)
                print("标题:",title)
                print("描述:",descript)
                getClickCount(a)
                resd = requests.get(a)
                resd.encoding = 'utf-8'
                soupd = BeautifulSoup(resd.text, 'html.parser')
                info = soupd.select('.show-info')[0].text
                author = info[info.find('作者:'):].split()[0].lstrip('作者:')
                source = info[info.find('来源:'):].split()[0].lstrip('来源:')
                photo = info[info.find('摄影:'):].split()[0].lstrip('摄影:')
                content = soupd.select('#content')[0].text
                print("作者:", author)
                print("来源:", source)
                print("摄影:", photo)
                print("正文:", content)
                #取一个例子
                break
    
    
    def getClickCount(newsurl2):
            clickurl = 'http://oa.gzcc.cn/api.php?op=count&id=9183&modelid=80'
            #获得点击次数
            sum=requests.get(clickurl).text.split('.html')[-1].lstrip("('").rstrip("');")
            print("点击次数:", sum)
            #正则表达式
            re.match('http://news.gzcc.cn/html/2018/xiaoyuanxinwen(.*).html', newsurl2).group(1).split('/')[1]
            num=re.search('\_(.*).html', newsurl2).group(1)
            print('新闻编号:', num)
    
    getNewDetail(newsurl)

    结果如下:

  • 相关阅读:
    Docker安装MySQL&Redis
    使用VirtualBox+Vagrant快速搭建Linux虚拟机环境
    Java集合工具类的一些坑,Arrays.asList()、Collection.toArray()...
    1.docker常用命令
    4. 带有延迟时间的Queue(DelayQueue)
    3. 基于优先级的Queue(PriorityBlockingQueue)
    2. 常见的Queue
    1. 模拟Queue
    14. 线程调度
    13. 线程池
  • 原文地址:https://www.cnblogs.com/1103a/p/8762250.html
Copyright © 2011-2022 走看看