六云

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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
import re
from bs4 import BeautifulSoup
from datetime import datetime

url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')


def getClickCount(newsUrl):
    clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id=9183&modelid=80'
    click = requests.get(clickUrl).text.split('.html')[-1].lstrip("('").rstrip("');")
    print("点击次数:", click)
    re.match('http://news.gzcc.cn/html/2018/xiaoyuanxinwen(.*).html', newsUrl).group(1).split('/')[1]
    print('新闻编号:', re.search('\_(.*).html', newsUrl).group(1))

def getNewDetail(newsUrl):
    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']  # 获取链接
            res = requests.get(a)
            res.encoding = 'utf-8'
            soupd = BeautifulSoup(res.text, 'html.parser')
            content = soupd.select('#content')[0].text
            description = news.select('.news-list-description')[0].text # 获取正文
            resd = requests.get(a)
            resd.encoding = 'utf-8'
            soupd = BeautifulSoup(resd.text, 'html.parser')
            info = soupd.select('.show-info')[0].text
            d = info.lstrip('发布时间:')[:19]
            dt = datetime.strptime(d, '%Y-%m-%d %H:%M:%S')
            author = info[info.find('作者:'):].split()[0].lstrip('作者:')
            source = info[info.find('来源:'):].split()[0].lstrip('来源:')
            photo = info[info.find('摄影:'):].split()[0].lstrip('摄影:')
            print("校园新闻首页新闻获取情况")
            print("新闻标题:", t)
            print("链接:", a)
            getClickCount(a)
            print("发布时间:", dt)
            print("文章作者:", author)
            print("文章来源:", source)
            print("摄影:", photo)
            print("文章描述:", description)
            print("文章正文:", content)
            break


getNewDetail(url)

运行效果如下:

 

posted on 2018-04-04 16:07  流XC  阅读(202)  评论(0编辑  收藏  举报