zoukankan      html  css  js  c++  java
  • 爬取校园新闻首页的新闻

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

    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    
    res = requests.get("http://news.gzcc.cn/html/xiaoyuanxinwen/")
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    for news in soup.select('li'):
        if len(news.select('.news-list-title')) > 0:
            r = news.select('.news-list-title')[0].text  #正文内容
            d = news.select('.news-list-info')[0].contents[0].text #新闻发布时间
            t = news.select('.news-list-info')[0].contents[1].text  #来源
            g = news.select('a')[0].attrs['href'] #链接
            print(r,d,t,g)

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

           法一:
    resd = requests.get(g) resd.encoding = 'utf-8' soupd = BeautifulSoup(resd.text, 'html.parser') x = soupd.select('.show-content')[0].text t1 = soupd.select('.show-info')[0].text.split() #每篇新闻的发布时间,作者,来源 print(t1) s = t1[0].lstrip('发布时间:') + " " + t1[1] #发布时间 s1 = t1[2].lstrip('作者:') #作者 s2 = t1[3].lstrip('审核:') #审核 s3 = t1[4].lstrip("来源:") #来源 print(s, s1, s2, s3)
           二:
    t2 = soupd.select('.show-info')[0].text print(t2) q = t2.lstrip('发布时间:')[:19] q1 = t2.split()[2].lstrip('作者:') print(q, q1)

    3. 将其中的发布时间由str转换成datetime类型。

            dati = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
            print(type(dati))
            print(dati, dati.strftime('%Y/%m/%d'))

    4. 将完整的代码及运行结果截图发布在作业上。

  • 相关阅读:
    Paxos算法理解
    JavaScript笔记
    JVM基础知识(二)
    JVM基础知识(一)
    书单
    centos6.3环境下升级python及MySQLdb的安装
    winform中button的image属性无法更改
    未能找到任何适合于指定的区域性或非特定区域性的资源
    Spring注解开发第十二讲--@Profile注解讲解
    Spring注解驱动第十一讲--引用Spring底层组件
  • 原文地址:https://www.cnblogs.com/cgz123/p/8710437.html
Copyright © 2011-2022 走看看