爬取校园新闻首页的新闻

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

 

posted @ 2018-04-02 22:32  201505060365张木贵  阅读(115)  评论(0编辑  收藏  举报