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 requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    import locale
    import re
    
    locale.setlocale(locale.LC_CTYPE, 'chinese')
    url = "http://news.gzcc.cn/html/xiaoyuanxinwen/"
    res = requests.get(url)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    
    
    def getClickCount(newsUrl):
        newsid = re.search(r"\_(.*).html", newsUrl).group(1)[-4:]
        clicktimesurl = ("http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80").format(newsid)
        clicktimes = int(requests.get(clicktimesurl).text.split(".html(")[-1].lstrip("'").rstrip("');"))
        return clicktimes
    
    
    def getNewsDetail(newsUrl):
        resdet = requests.get(newsUrl)
        resdet.encoding = 'utf-8'
        soupdet = BeautifulSoup(resdet.text, 'html.parser')
        contentdetail = soupdet.select('#content')[0].text
        showinfo = soupdet.select('.show-info')[0].text
        date = showinfo.lstrip("发布时间:")[:19]
        author = re.search('作者:((.{2,4}s){1,3})', showinfo).group(1)
        checker = re.search('审核:((.{2,4}s){1,3})', showinfo).group(1)
        source = re.search('来源:((.{2,20}s){1,3})', showinfo).group(1)
        clicktimes = getClickCount(address)
        dateTime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        print("发表时间:{0}  作者:{1}  审核:{2}  来源:{3}  点击次数:{4} 次".format(dateTime, author, checker, source, clicktimes))
        print(contentdetail)
    
    
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            title = news.select('.news-list-title')[0].text
            description = news.select('.news-list-description')[0].text
            info = news.select('.news-list-info')[0].text
            address = news.select('a')[0]['href']
            print("
    标题: {0}
    描述: {1}
    信息: {2}
    链接: {3}".format(title, description, info, address))
            getNewsDetail(address)
  • 相关阅读:
    Mina之session
    GNU C 、ANSI C、标准C、标准c++区别和联系
    SOCKET CLOSE_WAIT 搜集
    [转]二维数组和二级指针的传递问题
    Linux下C语言线程池的实现(1)
    MINA2 之日志配置
    mina里的死锁检测
    MINA2中的拆包组包的处理及一些方法
    void及void指针含义的深刻解析
    JS轻松实现单击文本框弹出选择日期
  • 原文地址:https://www.cnblogs.com/BennyKuang/p/8710195.html
Copyright © 2011-2022 走看看