• 爬取校园新闻首页的新闻


    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'))
            t=news.select('.news-list-title')[0].text
            dt=news.select('.news-list-info')[0].contents[0].text
            a=news.select('a')[0].attrs['href']
            print(dt,t,a)

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

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

    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    
    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:
            t = news.select('.news-list-title')[0].text
            dt = news.select('.news-list-info')[0].contents[0].text
            a = news.select('a')[0].attrs['href']
            print(dt,t,a)#爬取校园新闻首页新闻的标题、链接
            res2 = requests.get(a)
            res2.encoding = 'utf-8'
            soup2 = BeautifulSoup(res2.text, 'html.parser')
            te = soup2.select('#content')[0].text
            print(te)#爬取校园新闻首页新闻的正文
    
            ifd = soup2.select('.show-info')[0].text
            dt2 = ifd.lstrip('发布时间:')[:19]
            print(dt2)#获取新闻的发布时间
    
            i = ifd.find('作者:')
            if i>0:
                s = ifd[ifd.find('作者:'):].split()[0].lstrip('作者:')
                print(s)#获取新闻的作者。
    
            q = ifd.find('来源:')
            if q > 0:
                b = ifd[ifd.find('来源:'):].split()[0].lstrip('来源:')
                print(b)#获取新闻的来源。
    
            c = ifd.find('摄影:')
            if c > 0:
                n = ifd[ifd.find('摄影:'):].split()[0].lstrip('摄影:')
                print(n)#获取新闻的摄影。
    
            dtn = datetime.strptime(dt2,'%Y-%m-%d %H:%M:%S')#将其中的发布时间由str转换成datetime类型。
            print(dtn)
            break

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

  • 相关阅读:
    Codeforces 946D
    Codeforces 817F
    Codeforces 931F
    Codeforces 932D
    Graph HDU
    Chef and Graph Queries CodeChef
    Lucky Array Codeforces
    Calculation 2 HDU
    洛谷 P3455 [POI2007]ZAP-Queries || 洛谷P2522,bzoj2301
    洛谷 P2398 GCD SUM || uva11417,uva11426,uva11424,洛谷P1390,洛谷P2257,洛谷P2568
  • 原文地址:https://www.cnblogs.com/126lc/p/8694948.html
Copyright © 2020-2023  润新知