爬取校园新闻首页的新闻

1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。

import requests
from bs4 import BeautifulSoup
 
res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')
 
for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        d = news.select('.news-list-info')[0].contents[0].text #时间
        t = news.select('.news-list-title')[0].text #标题
        a = news.select('a')[0].attrs['href'] #URL
        print(d, t, a)

  运行结果图:

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

res2 = requests.get(a)
res2.encoding = 'utf-8'
soup2 = BeautifulSoup(res2.text,'html.parser')
x = soup2.select('.show-content')[0].text
info = soup2.select('.show-info')[0].text.split()
# print(soup2.select('#content')[0].text)
s = info[0].lstrip('发布时间:') + " " + info[1] #发布时间
zz = info[2].lstrip('作者:')  #作者
sh = info[3].lstrip('审核:')  #审核
ly = info[4].lstrip("来源:")  #来源
print(s,zz,sh,ly)

 运行结果图:

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

from datetime import datetime
time = '2018-04-01 11:57:00'
a = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
print(type(a))
print(a, a.strftime('%Y/%m/%d'))

 运行结果图:

 

 

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

import requests
from bs4 import BeautifulSoup
from datetime import datetime
res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')
 
for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        d = news.select('.news-list-info')[0].contents[0].text #时间
        t = news.select('.news-list-title')[0].text #标题
        a = news.select('a')[0].attrs['href'] #URL
        print(d,t,a)
        res2 = requests.get(a)
        res2.encoding = 'utf-8'
        soup2 = BeautifulSoup(res2.text,'html.parser')
        x = soup2.select('.show-content')[0].text
        info = soup2.select('.show-info')[0].text.split()
        # print(soup2.select('#content')[0].text)
        s = info[0].lstrip('发布时间:') + " " + info[1] #发布时间
        zz = info[2].lstrip('作者:')  #作者
        sh = info[3].lstrip('审核:')  #审核
        ly = info[4].lstrip("来源:")  #来源
        cc = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
        print(cc,type(cc))
        print(cc.strftime('%Y/%m/%d'),zz,sh,ly)

  

posted @ 2018-04-03 23:22  黄俊熙  阅读(115)  评论(0编辑  收藏  举报