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字符串,点击次数字符串。

    # -*- coding: UTF-8 -*-
    import requests
    from  bs4 import  BeautifulSoup
    from datetime import datetime
    import re
    
    #获取点击次数
    def getClickCount(newsUrl):
        newsId = re.findall('\_(.*).html', newsUrl)[0].split('/')[1]
        clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
        clickStr = requests.get(clickUrl).text
        count = re.search("hits').html('(.*)');",clickStr).group(1)
        return count
    
    
    # 获取新闻详情
    def getNewDetail(url):
        resd = requests.get(url)
        resd.encoding = 'utf-8'
        soupd = BeautifulSoup(resd.text, 'html.parser')
        info = soupd.select('.show-info')[0].text
        time = re.search('发布时间:(.*) xa0xa0 xa0xa0作者:', info).group(1)
        dtime = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
    
        print('链接:' + url)
        print('标题:' + title)
        print('发布时间:{}'.format(dtime))
        print('作者:' + re.search('作者:(.*)审核:', info).group(1))
        print('审核:' + re.search('审核:(.*)来源:', info).group(1))
        print('来源:' + re.search('来源:(.*)摄影:', info).group(1))
        print('摄影:' + re.search('摄影:(.*)点击', info).group(1))
        print('点击次数:' + getClickCount(a))
    
    
    newsUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(newsUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text,'html.parser')
    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            title = news.select('.news-list-title')[0].text
            #获取新闻模块链接
            a = news.a.attrs['href']
            #调用函数获取新闻正文
            getNewDetail(a)
            break

    运行结果截图:

  • 相关阅读:
    关于爬虫urllib.request模块、urllib.parse模块的基础使用
    爬取小视频网站视频并下载——场库网站视频批量下载
    关于json接口返回的数据不是json格式的处理方法——正则匹配
    存储型XSS靶场作业
    MSSQL-反弹注入
    显错注入四关
    课时53.video标签(掌握)
    课时50.51表单练习(理解)
    课时49.非input标签(掌握)
    课时48.表单标签-H5(了解)
  • 原文地址:https://www.cnblogs.com/xuyizhu/p/8707487.html
Copyright © 2011-2022 走看看