获取一篇新闻的全部信息
本次作业的要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894
给定一篇新闻的链接newsUrl,获取该新闻的全部信息标题、作者、发布单位、审核、来源发布时间:转换成datetime类型。
- newsUrl
- newsId(使用正则表达式re)
- clickUrl(str.format(newsId))
- requests.get(clickUrl)
- newClick(用字符串处理,或正则表达式)
- int()
整个过程包装成一个简单清晰的函数。
代码如下:
#!/usr/bin/env python # _*_ coding:utf-8 _* import re import requests from datetime import datetime from bs4 import BeautifulSoup # 获取新闻网页的id def newsid(url): n_id = re.match('http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0314/(.*).html',url).group(1) return n_id def clickcount(url): id = re.findall('(\d{1,5})',url)[-1] clickurl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id) res=requests.get(clickurl) click=res.text.split('.html')[-1].lstrip("('").rstrip("');") return click # 转换发布时间类型 def fabushijian(soup): date = soup.select('.show-info')[0].text.split()[0].split(':')[1] time = soup.select('.show-info')[0].text.split()[1] times = date + ' ' + time times = datetime.strptime(times,'%Y-%m-%d %H:%M:%S') return times if __name__ == '__main__': # 爬取网站的url url = 'http://news.gzcc.cn/html/2019/xiaoyuanxinwen_0314/10983.html' res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') title = soup.select('.show-title')[0].text auditor = soup.select('.show-info')[0].text.split()[3] comefrom = soup.select('.show-info')[0].text.split()[4] detail = soup.select('.show-content')[0].text author = soup.select('.show-info')[0].text.split()[2] newsid = newsid(url) time = fabushijian(soup) clicktime = clickcount(url) print(" 编号:" + newsid + '\n'" 标题:" + title + '\n', author + '\n', auditor + '\n',comefrom + '\n'" 正文:" + detail + '\n'" 次数:" + clicktime + '\n 发布时间: ', time)
运行结果如下: