• 爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离


    任务如下:

    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 requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    import re
    res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    
    
    # 获取新闻点击次数
    def getNewsId(url):
        newsId = re.findall(r'\_(.*).html', url)[0][-4:]
        clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
        clickRes = requests.get(clickUrl)
        # 利用正则表达式获取新闻点击次数
        clickCount = int(re.search("hits').html('(.*)');", clickRes.text).group(1))
        return clickCount
    
    
    
    def getNewDetail(newsUrl):
        # 读取新闻细节
        resDescript = requests.get(newsUrl)
        resDescript.encoding = "utf-8"
        soupDescript = BeautifulSoup(resDescript.text, 'html.parser')
    
        content = soupDescript.select(".show-content")[0].text  # 正文
        info = soupDescript.select(".show-info")[0].text  # info相关内容
        # 第一种方法 分离 message = info.split()
        # 第二种方法 用正则表达式
        time = re.search("发布时间:(.*) xa0xa0 xa0xa0作者:", info).group(1)
        author = re.search("作者:(.*)xa0xa0审核:", info).group(1)
        right = re.search("审核:(.*)xa0xa0来源:", info).group(1)
        resource = re.search('来源:(.*)xa0xa0xa0xa0摄影:', info).group(1)
        video = re.search("摄影:(.*)xa0xa0xa0xa0点击:", info).group(1)
        count = getNewsId(newsUrl)
        dateTime = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
    
        print('标题' + ': ' + title)
        print('概要' + ': ' + description)
        print('链接' + ': ' + a)
        print('正文' + ' :' + content)
        print('发布时间:{0}
    作者:{1}
    审核:{2}
    来源:{3}
    摄影:{4}
    点击次数:{5}'.format(dateTime, author, right, resource, video,count))
        print("
    ")
    
    
    
    for s in soup.select("li"):
        if len(s.select(".news-list-title"))>0:
            title = s.select(".news-list-title")[0].text #新闻标题
            description = s.select(".news-list-description")[0].text #新闻描述
            a = s.a.attrs["href"] #观看新闻细节
            getNewDetail(a)
  • 相关阅读:
    asp.net点击按钮下载图片而不是打开图片
    在事务中调用WebService一定程度上实现数据同步
    C#自定义Attribute的定义和获取简例
    开发ASP.NET下的MP3小偷程序
    Ajax 中XmlHttp 乱码 的解决方法 (UTF8,GB2312 编码 解码)
    MasterPage 类
    怎样成为优秀的软件测试员
    标准日本语动词大全
    什么是WSDL?
    ASP.NET程序中常用的三十三种代码
  • 原文地址:https://www.cnblogs.com/qazwsx833/p/8732737.html
Copyright © 2020-2023  润新知