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:
    #         print(news.select('.news-list-title'))
    
    
    for newc in soup.select('li'):
        if len(newc.select('.news-list-title'))>0:
            d=newc.select('a')[0].attrs['href']
            res1=requests.get(d)
            res1.encoding="utf-8"
            e=BeautifulSoup(res1.text,'html.parser')
            content=e.select('#content')[0].text
            show=e.select('.show-info')[0].text
            print(content,show)

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

    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            title = news.select('.news-list-title')[0].get_text()
            time =  news.select('.news-list-info span')[0].get_text()
            href = news.select('a')[0].attrs['href']
            print(time,title,href)
    
    
            res1 = requests.get(href)
            res1.encoding = "utf-8"
            soup = BeautifulSoup(res1.text, "html.parser")
            con = soup.select('#content')[0].tedtxt
            info = soup.select('.show-info')[0].get_text()
            dt = info.lstrip('发布时间:')[:19]
            dt2 = datetime.strptime(dt,'%Y-%m-%d %H:%M:%S')
            print(dt2)
             ///此处代码参考117李智濠
            i = info.find('来源:')
            if i>0:
                s =  info[info.find('来源:'):].split()[0].replace('来源:')
                print(s)
            a = info.find('作者:')
            if a > 0:
                l = info[info.find('作者:'):].split()[0].replace('作者:')
                print(l)
            y = info.find('摄影:')
            if y > 0:
                u = info[info.find('作者:'):].split()[0].replace('作者:')
                print(u)

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

    from datetime import datetime
            str ='2018-03-30 17:10:12'
            dt1 = datetime.strptime(str,'%Y-%M-%D %H:%M:%S').year
            now = datetime.now()
            type(now)
            now.strftime("%Y-%M-%D %H:%M:%S")
  • 相关阅读:
    CString与 char *之间的转换
    linux命令行打开图片
    CentOS7 NFS配置
    vs2010 Visula C++ 把CString 转换为string 类型
    1>LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
    mount 命令
    Centos7.0 Vmware10.0.3 网络桥接配置
    Notepad++ 连接远程 FTP 进行文件编辑
    安装PHP的mongodb驱动速记
    CentOS上安装MongoDB速记
  • 原文地址:https://www.cnblogs.com/severusandsusa/p/8705997.html
Copyright © 2011-2022 走看看