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:
            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")
  • 相关阅读:
    ssm利用ajax上传图片和参数
    ssm+rabbitmq 分布式实例
    ssh免密
    springboot中aop的尝试
    springboot中自定义属性实体类和应用
    滑动门--------实现导航栏背景图自适应文字内容多少
    嵌套块元素垂直外边距的合并(塌陷)
    vue项目处理时间戳问题
    vue项目中遇到的登录超时
    标签显示模式
  • 原文地址:https://www.cnblogs.com/bjdx1314/p/8691968.html
Copyright © 2011-2022 走看看