爬取校园新闻首页的新闻的详情

本文介绍了一个使用Python的requests和BeautifulSoup库爬取校园新闻的示例。该爬虫能够从指定网站获取新闻列表,并进一步抓取每篇新闻的详细信息,包括发布时间、作者、审核人、来源及点击次数。
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')


# 获取新闻点击次数
def getNewsId(url):
    newsId = re.findall(r'\_(.*).html', newsUrl)[0][-4:]
    clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
    clickRes = requests.get(clickUrl)
    # 利用正则表达式获取新闻点击次数
    clickCount = int(re.search("hits'\).html\('(.*)'\);", clickRes.text).group(1))
    return clickCount


# 获取新闻细节
def getNewsDetail(newsUrl):
    resd = requests.get(newsUrl)
    resd.encoding = 'utf-8'
    soupd = BeautifulSoup(resd.text, 'html.parser')

    content = soupd.select('#content')[0].text
    info = soupd.select('.show-info')[0].text
    # 调用getNewsId()获取点击次数
    count = getNewsId(newsUrl)
    print(info)
    # 识别时间格式
    date = re.search('(\d{4}.\d{2}.\d{2}\s\d{2}.\d{2}.\d{2})', info).group(1)
    # 识别一个至三个数据
    author = re.search('作者:((.{3}\s){1,3})', info).group(1)
    check = re.search('审核:((.{3}\s){1,3})', info).group(1)
    sources = re.search('来源:((.{3}\s){1,3})', info).group(1)
    # 用datetime将时间字符串转换为datetime类型
    dateTime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    # 利用format对字符串进行操作
    print('发布时间:{0}\n作者:{1}\n审核:{2}\n来源:{3}\n点击次数:{4}'.format(dateTime, author, check, sources, count))
    print(content)


for new in soup.select('li'):
    if len(new.select('.news-list-title')) > 0:
        title = new.select('.news-list-title')[0].text
        description = new.select('.news-list-description')[0].text
        newsUrl = new.select('a')[0]['href']

        print('标题:{0}\n内容:{1}\n链接:{2}'.format(title, description, newsUrl))
        # 调用getNewsDetail()获取新闻详情
        getNewsDetail(newsUrl)
        break

 

转载于:https://www.cnblogs.com/fzjKim/p/8762892.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值