作业要求来自于:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE2/homework/2894
给定一篇新闻的链接newsUrl,获取该新闻的全部信息
标题、作者、发布单位、审核、来源
发布时间:转换成datetime类型
点击:
- newsUrl
- newsId(使用正则表达式re)
- clickUrl(str.format(newsId))
- requests.get(clickUrl)
- newClick(用字符串处理,或正则表达式)
- int()
整个过程包装成一个简单清晰的函数。
尝试去爬取一个你感兴趣的网页。
# 获取一篇新闻的全部信息 import re import requests from bs4 import BeautifulSoup from datetime import datetime# 获取新闻id def newsnum(url):newsid = re.match('http://news.gzcc.cn/html/2019/meitishijie_0321/(.*).html', url).group(1)return newsid# 发布时间:datetime类型 def newstime(soup):newsdate = soup.select('.show-info')[0].text.split()[0].split(':')[1]newstime = soup.select('.show-info')[0].text.split()[1]time = newsdate + ' ' + newstimetime = datetime.strptime(time, '%Y-%m-%d %H:%M:%S')return time# 获取点击次数 def click(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 main(url):res = requests.get(url)res.encoding = 'utf-8'soup = BeautifulSoup(res.text, 'html.parser')#print(soup.select('.show-info')[0].text.split());print("新闻编号:" + newsnum(url)); # 新闻编号idprint("标题:" + soup.select('.show-title')[0].text); # 标题print("发布时间:" + str(newstime(soup))); # 发布时间print(soup.select('.show-info')[0].text.split()[2]); # 作者print(soup.select('.show-info')[0].text.split()[3]); # 审核print(soup.select('.show-info')[0].text.split()[4]); # 来源print("内容:" + soup.select('.show-content p')[0].text); # 内容returnurl = "http://news.gzcc.cn/html/2019/meitishijie_0321/11033.html" main(url)