获取一篇新闻的全部信息
给定一篇新闻的链接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):
clickurl='http://oa.gzcc.cn/api.php?op=count&id=10789&modelid=80'
res=requests.get(clickurl)
click=res.text.split('.html')[-1].lstrip("('").rstrip("');")
return click
#获取发布时间
def newsdt(url):
soup = BeautifulSoup(res.text,'html.parser')
showinfo = soup.select('.show-info')[0].text
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='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_1227/10789.html'
news(url)