爬取校园新闻首页的新闻

1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文、show-info。

import requests

from bs4 import BeautifulSoup

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

a=soup.select('li')[10].a.attrs['href']
print(a)

newsurl1=a
res2=requests.get(newsurl1)
res2.encoding='utf-8'
soup1=BeautifulSoup(res2.text,'html.parser')
t=soup1.select('#content')[0].text
t2=soup1.select('.show-info')[0].text

print(t)

print(t2)

2. 分析info字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。

t3=t2.split()
t4=t3[0]
print(t3)
print(t3[1])
t5=t4.lstrip('发布时间:')
t6=t3[2].lstrip('作者:')
t7=t3[3].lstrip('审核:')
t8=t3[4].lstrip('来源:')
print(t5)
print(t6)
print(t7)
print(t8)

3. 将字符串格式的发布时间转换成datetime类型

datetime1=t5+' '+t3[1]
print(datetime1)
d2=datetime.strptime(datetime1,"%Y-%m-%d %H:%M:%S")
print(d2)

4. 使用正则表达式取得新闻编号

newsurl2='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
newsurl3=re.search('(\d{2,}\.html)',newsurl2).group(1)
newsurl4=newsurl3.rstrip('.html')
print(newsurl4)

5. 生成点击次数的Request URL

url='http://oa.gzcc.cn/api.php?op=count&id=9183&modelid=80'
res3=requests.get(url).text
print(res3)

6. 获取点击次数

res4=res3.split('html')
res5=res4[-1].lstrip("('").rstrip("');")
print(res5)

7. 将456步骤定义成一个函数 def getClickCount(newsUrl):

def getClickCount(newsUrl):

newsurl2='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
newsurl3=re.search('(\d{2,}\.html)',newsurl2).group(1)
newsurl4=newsurl3.rstrip('.html')

newid='http://oa.gzcc.cn/api.php?op=count&id='+newsurl4+'&modelid=80'

res3=requests.get(newid).text
print(res3)
res4=res3.split('html')
res5=res4[-1].lstrip("('").rstrip("');")
print(res5)

8. 将获取新闻详情的代码定义成一个函数 def getNewDetail(newsUrl):

schoolurl='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
def getNewDetail(schoolurl):
res10=requests.get(schoolurl)
res10.encoding='utf-8'
soup10=BeautifulSoup(res10.text,'html.parser')
b=soup10.select('#content')[0].text
print(b)
getNewDetail(schoolurl)

9. 尝试用使用正则表达式分析show info字符串,点击次数字符串。

 t2=soup1.select('.show-info')[0].text

posted @ 2018-04-04 16:09  161蔡瑞奇  阅读(153)  评论(0编辑  收藏  举报