给定一篇新闻的链接newsUrl,获取该新闻的全部信息
标题、作者、发布单位、审核、来源
发布时间:转换成datetime类型
点击:
- newsUrl
- newsId(使用正则表达式re)
- clickUrl(str.format(newsId))
- requests.get(clickUrl)
- newClick(用字符串处理,或正则表达式)
- int()
整个过程包装成一个简单清晰的函数。
1 import requests 2 import re 3 from bs4 import BeautifulSoup 4 def click(url):#获取点击次数 5 id=re.findall('(\d{1,5})',url)[-1] 6 clickUrl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(id) 7 res=requests.get(clickUrl) 8 newsClick=res.text.split('.html')[-1].lstrip("('").rstrip("');") 9 return newsClick10 11 def newsdt(showinfo):#转换成datetime类型12 newsDate=showinfo.split()[0].split(':')[1]13 newsTime=showinfo.split()[1]14 newsDT=newsDate+' '+newsTime15 #newsDT=datetime.strptime(newsDT,'%Y-%m-%d %H:%M:%S')16 return newsDT17 18 def newsid(url):#获取新闻编号19 newsID=re.findall('(\d{1,5})',url)[-1]20 return newsID21 22 def news(url):23 res=requests.get(url)24 res.encoding='utf-8'25 soup=BeautifulSoup(res.text,'html.parser')26 title=soup.select('.show-title')[0].text27 showinfo=soup.select('.show-info')[0].text28 newsDT=newsdt(showinfo)29 author=soup.select('.show-info')[0].text.split()[2]#获取作者30 check=soup.select('.show-info')[0].text.split()[3]#获取审核31 comefrom=soup.select('.show-info')[0].text.split()[4]#获取来源32 detail=soup.select('.show-content ')[0].text#获取新闻的具体内容33 newsID=newsid(url)#获取新闻编号34 newsClick=click(url)#获取点击次数35 title='新闻标题:'+title36 newsClick='文章点击次数:'+newsClick37 newsID='新闻编号:'+newsID38 newsDT='发布日期:'+newsDT39 pr=(newsClick,title,newsDT,newsID,author,check,comefrom,detail)#输出新闻的各种信息40 return pr41 url='http://news.gzcc.cn/html/2019/jxky_0329/11100.html'42 print(news(url))