1. 用requests库和BeautifulSoup库,爬取校园新闻首页新闻的标题、链接、正文。
2. 分析字符串,获取每篇新闻的发布时间,作者,来源,摄影等信息。
3. 将其中的发布时间由str转换成datetime类型。
4. 将完整的代码及运行结果截图发布在作业上。
import requests
from bs4 import BeautifulSoup
from datetime import datetime
res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
for news in soup.select('li'):
if len(news.select('.news-list-title')) > 0:
t = news.select('.news-list-title')[0].text # 标题
a = news.select('a')[0].attrs['href'] # URL
res2 = requests.get(a)
res2.encoding = 'utf-8'
soup2 = BeautifulSoup(res2.text, 'html.parser')
c = soup2.select('.show-content')[0].text # 正文
print(t,a,c)
info = soup2.select('.show-info')[0].text.split()
# print(soup2.select('#content')[0].text)
s = info[0].lstrip('发布时间:') + " " + info[1] # 发布时间
zz = info[2].lstrip('作者:') # 作者
sh = info[3].lstrip('审核:') # 审核
ly = info[4].lstrip("来源:") # 来源
cc = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
print(cc, type(cc))
print(cc.strftime('%Y/%m/%d'), zz, sh, ly)
break;
