标签:alt text 新闻 encoding ptime source 使用 nbsp auth
给定一篇新闻的链接newsUrl,获取该新闻的全部信息
标题、作者、发布单位、审核、来源
发布时间:转换成datetime类型
点击:
整个过程包装成一个简单清晰的函数。
尝试去爬取一个你感兴趣的网页。
代码:
import re import requests from bs4 import BeautifulSoup from datetime import datetime # 点击次数 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) resClick = requests.get(clickUrl) newsClick = int (resClick.text.split(‘.html‘)[-1].lstrip("(‘").rstrip("‘);")) return newsClick # 获取时间 def newsdt(showinfo): newsDate = showinfo.split()[0].split(‘:‘)[1] newsTime = showinfo.split()[1] newsDT = newsDate+‘ ‘+newsTime dt = datetime.strptime(newsDT,‘%Y-%m-%d %H:%M:%S‘) return dt # 新闻信息 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 newsDT = newsdt(showinfo) #时间 newsClick = click(url) #点击次数 news = print(newsTitle,newsDT,author,auditor,source,newsClick) return news url=‘http://news.gzcc.cn/html/2019/xibusudi_0328/11088.html‘ news(url)
运行结果:
标签:alt text 新闻 encoding ptime source 使用 nbsp auth
原文地址:https://www.cnblogs.com/mgf69/p/10637252.html