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 requestfrom bs4 import BeautifulSoup
import requests
import re
from bs4 import BeautifulSoup
from datetime import datetime
url = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')
#获取新闻详情
def getNewDetail(Url):
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']
resd = requests.get(a)
resd.encoding = 'utf-8'
soupd = BeautifulSoup(resd.text, 'html.parser')
content = soupd.select('#content')[0].text
s = soupd.select('.show-info')[0].text
print("标题:",title)
print("链接:",a)
print("描述:",description)
print("正文:",content)
# print(s)
#获取发布时间,作者,审核,来源,摄影等信息
t = soupd.select('.show-info')[0].text[0:24].lstrip('发布时间:')
#将字符串格式的发布时间转换成datetime类型
dt = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
print("发布时间:",dt)
print(soupd.select('.show-info')[0].text[30:36])
print(soupd.select('.show-info')[0].text[38:45])
print(soupd.select('.show-info')[0].text[46:53])
print(soupd.select('.show-info')[0].text[56:61])
getClickCount(a)
break
#h获取点击次数
def getClickCount(Url):
clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id=9183&modelid=80'
c = requests.get(clickUrl).text.split('html')[-1].lstrip("'(").rstrip(")';")
print("点击次数:",c)
getNewDetail(url)