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:
    
            break
    
    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            t = news.select('.news-list-title')[0].text
            print(t)
            break
    

     链接

    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:
    
            break
    
    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            t = news.select('.news-list-title')[0].text
            link = news.select('a')[0].attrs['href']
            print(link)
            break

    正文

            resd = requests.get(link)
            resd.encoding='utf-8'
            soupd = BeautifulSoup(resd.text,'html.parser')
            d = soupd.select('#content')[0].text
            print(d)
            break

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

    发布时间

    info = soupd.select('.show-info')[0].text 
    t1 = info.lstrip('发布时间:')[:19]
    print(t1)

    作者来源摄影等

    s = info[info.find('来源:'):].split()[0].lstrip('来源:')
    print(s)
    
    
    

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

         from datetime import datetime
            dt = datetime.strptime(t1,'%Y-%m-%d %H:%M:%S')
            now = datetime.now()
    
            print(dt)
    
  • 相关阅读:
    将文件放到Android模拟器的SD卡中的两种解决方法
    Response JSON数据返回
    jAVA 得到Map价值
    【动态规划】leetcode
    思考互联网分布式系统
    Cocos2d-x数据持久-变更数据
    小程序猿都找到了工作经验的方式
    抄360于Launcher浮动窗口的屏幕显示内存使用情况(改进版)
    vb.net窗口继承(房重建知识汇总)
    Spring该讲座
  • 原文地址:https://www.cnblogs.com/0056a/p/8692279.html
Copyright © 2011-2022 走看看