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


    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:
            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)

    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            t = news.select('.news-list-title')[0].text
            a = news.select('a')[0].attrs['href']
            print(a)
            resd = requests.get(a)
            resd.encoding ='utf-8'
            soupd = BeautifulSoup(resd.text,'html.parser')
            print(soupd.select('#content')[0].text)
            break

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

    for news in soup.select('li'):
        if len(news.select('.news-list-title'))>0:
            t = news.select('.news-list-title')[0].text
            a = news.select('a')[0].attrs['href']
            print(a)
            resd = requests.get(a)
            resd.encoding ='utf-8'
            soupd = BeautifulSoup(resd.text,'html.parser')
            print(soupd.select('.show-info')[0].text)
            break

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

    from _datetime import datetime
    str = '2018-03-30 17:10:12'
    dt =datetime.strptime(str,'%Y-%m-%d %H:%M:%S')
    now = datetime.now()
    type(now)
    now.strftime("%Y-%m-%d %H:%M:%S")
  • 相关阅读:
    python易混易乱(2)
    python易混易乱(1)
    #1062 – Duplicate entry ‘1’ for key ‘PRIMARY’
    关于 flask 实现数据库迁移以后 如何根据创建的模型类添加新的表?
    Linux同步互斥(Peterson算法,生产者消费者模型)
    正则表达式(Python)
    进程间通信
    CSS常见简写规则整理
    Django Model
    Django杂记
  • 原文地址:https://www.cnblogs.com/li123/p/8696362.html
Copyright © 2020-2023  润新知