获取一篇新闻的全部信息
给定一篇新闻的链接newsUrl,获取该新闻的全部信息
标题、作者、发布单位、审核、来源
发布时间:转换成datetime类型
点击:
- newsUrl
- newsId(使用正则表达式re)
- clickUrl(str.format(newsId))
- requests.get(clickUrl)
- newClick(用字符串处理,或正则表达式)
- int()
整个过程包装成一个简单清晰的函数。
尝试去爬取一个你感兴趣的网页。
1 import re 2 import requests 3 from bs4 import BeautifulSoup 4 from datetime import datetime 5 6 #获取新闻的所有信息 7 def news(url): 8 res = requests.get(url) 9 res.encoding = 'utf-8' 10 soup = BeautifulSoup(res.text,'html.parser') 11 newsTitle = soup.select('.show-title')[0].text #标题 12 author = soup.select('.show-info')[0].text.split()[2] #作者 13 auditor = soup.select('.show-info')[0].text.split()[3] #审核 14 source = soup.select('.show-info')[0].text.split()[4] #来源 15 showinfo = soup.select('.show-info')[0].text 16 newsday = newsdt(showinfo) #时间 17 newsclick = click(url) #点击次数 18 news = print(newsTitle,newsday,author,auditor,source,newsclick) 19 return news 20 21 #获取点击量 22 def click(url): 23 clickurl='http://oa.gzcc.cn/api.php?op=count&id=10789&modelid=80' 24 res=requests.get(clickurl) 25 click=res.text.split('.html')[-1].lstrip("('").rstrip("');") 26 return click 27 28 #获取发布时间 29 def newsdt(url): 30 soup = BeautifulSoup(res.text,'html.parser') 31 showinfo = soup.select('.show-info')[0].text 32 newsdate=showinfo.split()[0].split(':')[1] 33 newstime=showinfo.split()[1] 34 newsday=newsdate+' '+newstime 35 dt=datetime.strptime(newsday,'%Y-%m-%d %H:%M:%S') 36 return dt 37 38 39 40 url='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_1227/10789.html' 41 news(url)
运行结果截图
posted on 2019-04-02 10:40 kenda_yellow 阅读(204) 评论(0) 编辑 收藏 举报