获取一篇新闻的全部信息
给定一篇新闻的链接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 def news(url): res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') newsTitle = soup.select('.show-title')[0].text author = soup.select('.show-info')[0].text.split()[2] auditor = soup.select('.show-info')[0].text.split()[3] source = soup.select('.show-info')[0].text.split()[4] showinfo = soup.select('.show-info')[0].text newsday = newsdt(showinfo) newsclick = click(url) news = print(newsTitle, newsday, author, auditor, source, newsclick) return news def click(url): id=int(re.findall('_(.*).html',url)[0].split('/')[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 newsdt(showinfo): newsdate = showinfo.split()[0].split(':')[1] newstime = showinfo.split()[1] newsday = newsdate + ' ' + newstime dt = datetime.strptime(newsday, '%Y-%m-%d %H:%M:%S') return dt url = 'https://www.chinanews.com' news(url)