python爬取学校新闻_python-爬取校园新闻首页的新闻

1.作业代码

importrequestsfrom bs4 importBeautifulSoupfrom datetime importdatetime#========================================================================#1.用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。#========================================================================

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

res.encoding='utf-8'soup=BeautifulSoup(res.text,'html.parser')for news in soup.select('li'):if len(news.select('.news-list-title'))>0:

pert=news.select('.news-list-title')[0].text #pertitle 每则新闻题目

perdt=news.select('.news-list-info')[0].contents[0].text #perDetail 每则新闻详细内容

perhref=news.select('a')[0].attrs['href'] #perHref 每则新闻源链接

#————————————爬取子页面内容——————————————————————————

perdetail=requests.get(perhref)

perdetail.encoding='utf-8'soupDetail=BeautifulSoup(perdetail.text,'html.parser')

textContent=soupDetail.select('#content')[0].text#————————————输出内容——————————————

print('题目:',pert)print('发布时间:',perdt)print('源页面:',perhref)print('正文内容:',textContent)break;#=============================================================#2.分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。#=============================================================

info=soupDetail.select('.show-info')[0].textcatagory=['发布时间:','审核:','作者:','摄影:','来源:','点击:']

i=0while(i

valid=info.find(catagory[i])if(valid>=0):

s=info[info.find(catagory[i]):].split()[0].lstrip(catagory[i])#=============================================================#3.将其中的发布时间由str转换成datetime类型。#=============================================================

if(valid>0 and i==0):

timeC=datetime.strptime(s,'%Y-%m-%d %H:%M:%S')print(catagory[i]+s)

i=i+1

2.结果截图

1024144-20180403212648494-850534336.png中间省略若干新闻报道内容...暂爬取新闻第一页作示例。若源代码第31行的 break 注释掉,能够爬取更多的新闻页面。

1024144-20180403213259447-1218847911.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值