爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离

要求:

  1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文、show-info。
  2. 分析info字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
  3. 将字符串格式的发布时间转换成datetime类型
  4. 使用正则表达式取得新闻编号
  5. 生成点击次数的Request URL
  6. 获取点击次数
  7. 将456步骤定义成一个函数 def getClickCount(newsUrl):
  8. 将获取新闻详情的代码定义成一个函数 def getNewDetail(newsUrl):
  9. 尝试用使用正则表达式分析show info字符串,点击次数字符串。

根据上面要求,代码如下:

import  requests
from bs4 import BeautifulSoup
from datetime import datetime
import re

def getClickCount(newurl):   #获取点击次数
    newId = re.search('_(.*)/(.*).html', newurl).group(2)
    clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newId)
    clickStr = requests.get(clickUrl).text
    return(re.search("hits'\).html\('(.*)'\);",clickStr).group(1))


def getNewDetail(news):
    for new in news:
        print('新闻标题:' + new.select('.news-list-title')[0].text)
        newurl = new.select('a')[0].attrs['href']
        print('链接:' + newurl)
        resp = requests.get(newurl)
        resp.encoding = 'utf-8'
        soup = BeautifulSoup(resp.text, 'html.parser')
        show_info = soup.select('.show-info')[0].text

        time = re.search('发布时间:(.*) \xa0\xa0 \xa0\xa0作者:', show_info).group(1)
        dtime = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
        print('发布时间:{}'.format(dtime))
        print('作者:' + re.search('作者:(.*)审核:', show_info).group(1))
        print('审核:' + re.search('审核:(.*)来源', show_info).group(1))
        print('点击次数:' +     getClickCount(newurl))
        print('新闻正文:' + soup.select('#content')[0].text)




newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(newsurl)

res.encoding='utf-8'

soup=BeautifulSoup(res.text,'html.parser')

news=soup.select('.news-list > li')
getNewDetail(news)

运行结果如下:

 

posted @ 2018-04-09 14:10  183区展伯  阅读(153)  评论(0编辑  收藏  举报