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


    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")
  • 相关阅读:
    sonarqube添加C和C++语言
    sonarqube代码质量分析神器安装和使用
    sonarqube8.8汉化教程
    sonarqube代码分析平台踩坑指南
    解决Windows下PowerShell无法进入Python虚拟环境
    人工智能识别图片入门
    Python深拷贝和浅拷贝解读
    白嫖微软Azure12个月服务器
    Jmeter分布式压测
    Python+Appium实现自动抢微信红包
  • 原文地址:https://www.cnblogs.com/1940370572QQ/p/8698347.html
Copyright © 2020-2023  润新知