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

Posted 144+粱肇森

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离相关的知识,希望对你有一定的参考价值。

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 locale
import re
locale.setlocale(locale.LC_CTYPE,\'chinese\')
newsurl = \'http://news.gzcc.cn/html/xiaoyuanxinwen/\'
req = requests.get(newsurl) #返回response
req.encoding = \'utf-8\'
soup = BeautifulSoup(req.text, \'html.parser\')

def getClickCount(newsUrl):   #获取点击次数
    newsId = re.findall(\'\\_(.*).html\', newsUrl)[0].split(\'/\')[1]   #使用正则表达式取得新闻编号
    clickUrl = \'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80\'.format(newsId)
    clickStr = requests.get(clickUrl).text
    return(re.search("hits\'\\).html\\(\'(.*)\'\\);",clickStr).group(1))

def getNewDetail(newsUrl):   #获取新闻详情
    resd = requests.get(newsUrl)  # 返回response
    resd.encoding = \'utf-8\'
    soupd = BeautifulSoup(resd.text, \'html.parser\')
    print(\'标题:\' + title)
    print(\'描述:\' + description)
    print(\'链接:\' + newsUrl)
    info = soupd.select(\'.show-info\')[0].text
    time = re.search(\'发布时间:(.*) \\xa0\\xa0 \\xa0\\xa0作者:\', info).group(1)
    dtime = datetime.strptime(time, \'%Y-%m-%d %H:%M:%S\')   #将字符串格式的发布时间转换成datetime类型
    print(\'发布时间:{}\'.format(dtime))
    print(\'作者:\' + re.search(\'作者:(.*)审核:\', info).group(1))
    print(\'审核:\' + re.search(\'审核:(.*)来源:\', info).group(1))
    print(\'来源:\' + re.search(\'来源:(.*)摄影:\', info).group(1))
    print(\'摄影:\' + re.search(\'摄影:(.*)点击\', info).group(1))
    print(\'点击次数:\' + getClickCount(a))
    print(\'正文:\'+soupd.select(\'.show-content\')[0].text)

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

 

运行截图:

 

以上是关于爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离的主要内容,如果未能解决你的问题,请参考以下文章

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

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

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

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

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

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