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

    1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
    
    import requests
    from bs4 import BeautifulSoup
    url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
    res = requests.get(url)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    
    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            d = news.select('.news-list-info')[0].contents[0].text  #时间
            t = news.select('.news-list-title')[0].text  #标题
            a = news.select('a')[0].attrs['href']   #连接
            print(d, t, a)      
            # 通过连接获取新闻网页
            res2 = requests.get(a)
            res2.encoding = 'utf-8'
            soup2 = BeautifulSoup(res2.text, 'html.parser')
            # 取得新闻正文
            z=soup2.select('#content')[0].text
            print(z)
            break
    

      

    2. 分析字符串,获取每篇新闻的发布时间,作者,来源等信息。
    
     #取得发布时间、作者等数据项
            info=soup2.select('.show-info')[0].text
            # print(info)
            dt = info.lstrip('发布时间:')[:19]
            at = info[info.find('作者:'):].split()[0].lstrip('作者:')
            sh = info[info.find('审核:'):].split()[0].lstrip('审核:')
            ly = info[info.find('来源:'):].split()[0].lstrip('来源:')
            print(dt, at, sh, ly)
    

      

    3. 将其中的发布时间由str转换成datetime类型。
    
    from datetime import datetime
            dati = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
            print(dati, dati.strftime('%Y/%m/%d'))
    

      

  • 相关阅读:
    一则自用iptables例子解释
    SVN配置钩子文件限制提交文件时必须填写更新日志
    Nginx反向代理配置配置实例
    mysql 物理数据存放
    VisualVM、JConsole
    Rabbitmq
    pdm画表间结构
    tomcat jvm 参数优化
    【转载】Java导入导出excel
    【转载】使用 Google Guava 美化你的 Java 代码
  • 原文地址:https://www.cnblogs.com/wenjian1027/p/8710931.html
Copyright © 2011-2022 走看看