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

    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    import re
    url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(url)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    
    
    def getClick(newsUrl):
        newId = re.search('\_(.*).html', newsUrl).group(1).split('/')[1]
        click = requests.get('http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newId))
        return click.text.split('.html')[-1].lstrip("('").rstrip("');")
    
    
    def getNews(newsUrl):
        f = re.search('作者:((.{3}s){1,3})', info).group(1)
        date = re.search('(d{4}.d{2}.d{2}sd{2}.d{2}.d{2})', info).group(1)
        i = re.search('审核:((.{3}s){1,3})', info).group(1)
        l = re.search('来源:((.{3}s){1,3})', info).group(1)
        m = re.search('摄影:((..{3}s){1,3})',info).group(1)
        count = getClick(newsUrl)
        dateTime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
        print('发布时间:{0}'.format(dateTime))
        print('作者:{0}'.format(f))
        print('审核:{0}' .format(i))
        print('来源:{0}' .format(l))
        print('摄影:{0}' .format(m))
        print('点击:{0}' .format(count) + '')
    
    
    
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            link = news.a.attrs['href']
            t = news.select('.news-list-title')[0].text
            d = news.select('.news-list-description')[0].text
            newsUrl = news.select('a')[0]['href']
            res = requests.get(newsUrl)
            res.encoding = 'utf-8'
            soupb = BeautifulSoup(res.text, 'html.parser')
            info = soupb.select('.show-info')[0].text
            e = soupb.select('.show-content')[0].text
    
            print('标题:' + t)
            print('链接:' + newsUrl)
            print('描述:' + d)
            print('正文:' + e)
            getNews(newsUrl)
            break
     
    

  • 相关阅读:
    MySQL的字符编码体系(一)——数据存储编码
    poj 1659 Frogs' Neighborhood 度序列可图化 贪心
    POJ 1083 && HDU 1050 Moving Tables (贪心)
    cocos2d-x wp8 中文显示问题
    Linux多线程编程
    how tomcat works 五 servlet容器 上
    SecureCRT 选择Courier New等其他字体.
    如何设置secureCRT的鼠标右键为弹出文本操作菜单功能
    SecureCRT中文显示乱码
    ZooKeepr日志清理
  • 原文地址:https://www.cnblogs.com/170he/p/8763050.html
Copyright © 2011-2022 走看看