获取全部校园新闻

1.取出一个新闻列表页的全部新闻 包装成函数。

2.获取总的新闻篇数,算出新闻总页数。

3.获取全部新闻列表页的全部新闻详情。

 

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

# 获取新闻点击次数
def getNewsId(url):
    newsId = re.search(r'\_\d{4}\/((.*)).html', url).group(1)
    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)
    # 识别时间格式
    date = re.search('(\d{4}.\d{2}.\d{2}\s\d{2}.\d{2}.\d{2})', info).group(1)
    # 识别一个至三个数据
    if(info.find('作者:')>0):
        author = re.search('作者:((.{2,4}\s|.{2,4}、|\w*\s){1,3})', info).group(1)
    else:
        author = ''
    if(info.find('审核:')>0):
        check = re.search('审核:((.{2,4}\s){1,3})', info).group(1)
    else:
        check = ''
    if(info.find('来源:')>0):
        sources = re.search('来源:(.*)\s*摄|点', info).group(1)
    else:
        sources = ''
    if (info.find('摄影:') > 0):
        photo = re.search('摄影:(.*)\s*点', info).group(1)
    else:
        photo = ''
    # 用datetime将时间字符串转换为datetime类型
    dateTime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    # 利用format对字符串进行操作
    print('发布时间:{0}\n作者:{1}\n审核:{2}\n来源:{3}\n摄影:{4}\n点击次数:{5}'.format(dateTime, author, check, sources, photo, count))
    print(content)


def getListPage(listUrl):
    res = requests.get(listUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')

    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


listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
getListPage(listUrl)
res = requests.get(listUrl)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
listCount = int(soup.select('.a1')[0].text.rstrip(''))//10+1

for i in range(2,listCount):
    listUrl= 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    getListPage(listUrl)

 

4.找一个自己感兴趣的主题,进行数据爬取,并进行分词分析。不能与其它同学雷同。

爬取网易科技频道IT专题:

 

 代码:

import requests, re, jieba
from bs4 import BeautifulSoup
from datetime import datetime

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

    content = soupd.select('#endText')[0].text
    info = soupd.select('.post_time_source')[0].text
    date = re.search('(\d{4}.\d{2}.\d{2}\s\d{2}.\d{2}.\d{2})', info).group(1)  # 识别时间格式
    dateTime = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')  # 用datetime将时间字符串转换为datetime类型
    sources = re.search('来源:\s*(.*)', info).group(1)
    keyWords = getKeyWords(content)
    print('发布时间:{0}\n来源:{1}'.format(dateTime, sources))
    print('关键词:{}、{}、{}'.format(keyWords[0], keyWords[1], keyWords[2]))
    print(content)

# 通过jieba分词,获取新闻关键词
def getKeyWords(content):
    content = ''.join(re.findall('[\u4e00-\u9fa5]', content))  # 通过正则表达式选取中文字符数组,拼接为无标点字符内容
    wordSet = set(jieba._lcut(content))
    wordDict = {}
    for i in wordSet:
        wordDict[i] = content.count(i)
    deleteList, keyWords = [], []
    for i in wordDict.keys():
        if len(i) < 2:
            deleteList.append(i)  # 去掉单字无意义字符
    for i in deleteList:
        del wordDict[i]
    dictList = list(wordDict.items())
    dictList.sort(key=lambda item: item[1], reverse=True)  # 排序,返回前三关键字
    for i in range(3):
        keyWords.append(dictList[i][0])
    return keyWords

# 获取一页的新闻
def getListPage(listUrl):
    res = requests.get(listUrl)
    res.encoding = 'gbk'
    soup = BeautifulSoup(res.text, 'html.parser')
    for new in soup.select('#news-flow-content')[0].select('li'):
        newsUrl = new.select('a')[0]['href']
        title = new.select('a')[0].text
        print('标题:{0}\n链接:{1}'.format(title, newsUrl))
        getNewsDetail(newsUrl)  # 调用getNewsDetail()获取新闻详情
        break  # z只获取单个新闻,若要获取整页则去掉break

listUrl = 'http://tech.163.com/it/'
getListPage(listUrl)  # 获取首页新闻
for i in range(2, 20):  # 因为网易新闻频道只存取20页新闻,直接设置20
    listUrl = 'http://tech.163.com/special/it_2016_%02d/' % i  # 填充新闻页,页面格式为两位数字字符
    getListPage(listUrl)

结果截图:

 

来源:http://www.cnblogs.com/171-LAN/p/8794424.html


智能推荐

爬取全部的校园新闻

 本次作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3002 0.从新闻url获取点击次数,并整理成函数 newsUrl newsId(re.search()) clickUrl(str.format()) requests.get(clickUrl) re.search()/.split() str.l...

爬取全部的校园新闻

作业来源于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2941 1.从新闻url获取新闻详情: 字典,anews 2.从列表页的url获取新闻url:列表append(字典) alist 3.生成所页列表页的url并获取全部新闻 :列表extend(列表) allnews *每个同学爬学号尾数开始的10个列表页 4.设置合理的爬...

获取一篇新闻的全部信息

获取一篇新闻的全部信息 作业要求来自于https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894 给定一篇新闻的链接newsUrl,获取该新闻的全部信息 标题、作者、发布单位、审核、来源 发布时间:转换成datetime类型 点击: newsUrl newsId(使用正则表达式re) clickUrl(str.format(newsId...

作业八:获取一篇新闻的全部信息

给定一篇新闻的链接newsUrl,获取该新闻的全部信息 标题、作者、发布单位、审核、来源 发布时间:转换成datetime类型 点击: newsUrl newsId(使用正则表达式re) clickUrl(str.format(newsId)) requests.get(clickUrl) newClick(用字符串处理,或正则表达式) int() 整个过程包装成一个简单清晰的函数。  ...

获取一篇新闻的全部信息

作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894 给定一篇新闻的链接newsUrl,获取该新闻的全部信息 标题、作者、发布单位、审核、来源 发布时间:转换成datetime类型 点击: newsUrl newsId(使用正则表达式re) clickUrl(str.format(newsId)) requests.ge...

猜你喜欢

获取一篇新闻的全部信息

作业要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894 给定一篇新闻的链接newsUrl,获取该新闻的全部信息 标题、作者、发布单位、审核、来源 发布时间:转换成datetime类型 点击: newsUrl newsId(使用正则表达式re) clickUrl(str.format(newsId)) requests...

爬取校园新闻

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

爬取校园新闻首页的新闻

1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。 2. 分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。   3. 将其中的发布时间由str转换成datetime类型。 4. 将完整的代码及运行结果截图发布在作业上。  ...

无意中发现看书也是一种美

2012年4月25日晚,翻翻自己喜欢的一门语言学习书(python参考手册),无意中发现书中夹着之前的明信片(有一次和同事一起去前门邓丽君音乐生活馆留下来的),感觉学习也是一种美!于是乎拍下这不经意的时刻,哈哈!...

香橙派OrangePi PC Plus开发板连接USB以太网卡测试说明

1) 目前测试过能用的 USB 以太网卡如下所示,其中 RTL8153 USB 千兆网卡插入开 发板的 USB 2.0 Host 接口中测试可以正常使用,但是速率是达不到千兆的,这点请 注意   2) 首先将 USB 网卡插入开发板的 USB 接口中,然后在 USB 网卡中插入网线,确 保网线能正常上网,如果通过 dmesg 命令可以看到下面的 log 信息,说明 USB 网卡...

问答精选

How to extract beta coefficients for interaction effect in R?

I am examining the interaction between a continuous variable (bloodq) and a categorical variable with three levels (ER, RB, and WB). In order to see how the betas differ across tissue types, I would l...

what is the difference between Flatten() and GlobalAveragePooling2D() in keras

I want to pass the output of ConvLSTM and Conv2D to a Dense Layer in Keras, what is the difference between using global average pooling and flatten Both is working in my case. That both seem to work d...

How to invoke a test step with inputs at runtime from groovy script in SOAP UI?

I am writing a validation groovy script for a test step, intended to test a SOAP Web Service. Now, I want to call the same test step, with different input value from the groovy script. Is it possible?...

Wicket pagestore results wrong page

I have a problem with my web application with wicket. I am using wicket 6.14. I can't say exactly what the problem is, but I can describe the problem. I am using a self written pagestore, which uses h...

Unity load files from outside of resources folder

In unity is it possible to load a resource that is out side of the resources folder. I want the user to be able to set a textAsset variable from a file outside of the Assets directory entirely. You ca...

相关问题

相关文章

热门文章

推荐文章

相关标签

推荐问答